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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With