android – 如何使用服务中的asynctask写入内部存储中的文件?

我不能在服务中的asynctask中使用getFilesDir().

我看到这篇文章:

Android: Writing to a file in AsyncTask

它解决了活动中的问题,但我找不到在服务中执行此操作的方法.

如何使用服务中的asynctask写入内部存储文件?

这是我在asynctask中的代码:

  File file = new File(getFilesDir() + "/IP.txt");

最佳答案 Service和Activity都从ContextWrapper扩展,因此它有getFilesDir()方法.将服务实例传递给AsyncTask对象将解决它.

就像是:

File file = new File(myContextRef.getFilesDir() + "/IP.txt");

当您创建AsyncTask时,传递当前Service的引用(我假设您正在从Service创建AsyncTaskObject):

import java.io.File;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    protected void useFileAsyncTask() {
        FileWorkerAsyncTask task = new FileWorkerAsyncTask(this);
        task.execute();
    }

    private static class FileWorkerAsyncTask extends AsyncTask<Void, Void, Void> {

        private Service myContextRef;

        public FileWorkerAsyncTask(Service myContextRef) {
            this.myContextRef = myContextRef;
        }

        @Override
        protected Void doInBackground(Void... params) {
            File file = new File(myContextRef.getFilesDir() + "/IP.txt");
            // use it ...
            return null;
        }
    }
}
点赞