サービス内にある asynctask で getFilesDir() を使用できません。この投稿を見ました: Android: AsyncTask のファイルへの書き込み アクティビティで問題を解決しますが、サービスでこれを行う方法が見つかりません。サービスで asynctask を使用して内部ストレージ ファイルに書き込む方法は? これは asynctask の私のコードです:
File file = new File(getFilesDir() + "/IP.txt");
サービス内にある asynctask で getFilesDir() を使用できません。この投稿を見ました: Android: AsyncTask のファイルへの書き込み アクティビティで問題を解決しますが、サービスでこれを行う方法が見つかりません。サービスで asynctask を使用して内部ストレージ ファイルに書き込む方法は? これは asynctask の私のコードです:
File file = new File(getFilesDir() + "/IP.txt");
両方ともService
からもActivity
拡張するContextWrapper
ため、getFilesDir()
メソッドがあります。Service のインスタンスをAsyncTask
object に渡すと解決します。
何かのようなもの:
File file = new File(myContextRef.getFilesDir() + "/IP.txt");
AsyncTask を作成するときは、現在の Service の参照を渡します ( AsyncTaskObject
from Service を作成していると思います):
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;
}
}
}
getFileDir()
サービスを開始するときは、次のように提供される文字列パスを渡す必要があると思います。
Intent serviceIntent = new Intent(this,YourService.class);
serviceIntent.putExtra("fileDir", getFileDir());
あなたのサービスインonStart
メソッドでは、
Bundle extras = intent.getExtras();
if(extras == null)
Log.d("Service","null");
else
{
Log.d("Service","not null");
String fileDir = (String) extras.get("fileDir");
}