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

Rea*_*deo 5 service android android-asynctask

我不能在服务中的asynctask中使用getFilesDir()。我看到了这篇文章: Android:在AsyncTask中写入文件 它解决了活动中的问题,但是我找不到在服务中执行此操作的方法。如何在服务中使用asynctask写入内部存储文件?这是我在asynctask中的代码:

  File file = new File(getFilesDir() + "/IP.txt");
Run Code Online (Sandbox Code Playgroud)

gun*_*nar 2

两者Service兼而有之ActivityContextWrapper故有getFilesDir()方法。将 Service 的实例传递给AsyncTask对象即可解决该问题。

就像是:

File file = new File(myContextRef.getFilesDir() + "/IP.txt");
Run Code Online (Sandbox Code Playgroud)

当您创建 AsyncTask 时,传递当前服务的引用(我想您正在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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)