I can't use the getFilesDir() in an asynctask which is in a service.
I saw this post:
Android: Writing to a file in AsyncTask
It solves the problem in an activity but i dont find a way to do this in a service.
How to write to an internal storage file with an asynctask in a service?
This is my code in the asynctask:
File file = new File(getFilesDir() + "/IP.txt");
Both Service
and Activity
extend from ContextWrapper
as well, so it has getFilesDir()
method. Passing an instance of Service to AsyncTask
object will solve it.
Something like:
File file = new File(myContextRef.getFilesDir() + "/IP.txt");
When you're creating the AsyncTask pass a reference of current Service (I suppose you're creating the 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;
}
}
}
I think when you start your service, you should pass String path which getFileDir()
provides as follow.
Intent serviceIntent = new Intent(this,YourService.class);
serviceIntent.putExtra("fileDir", getFileDir());
In your service in onStart
method,
Bundle extras = intent.getExtras();
if(extras == null)
Log.d("Service","null");
else
{
Log.d("Service","not null");
String fileDir = (String) extras.get("fileDir");
}