How To Write To A File In The Internal Storage With An Asynctask In A Service?
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
Solution 1:
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:
Filefile=newFile(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;
publicclassMyServiceextendsService {
@Overridepublic IBinder onBind(Intent intent) {
returnnull;
}
protectedvoiduseFileAsyncTask() {
FileWorkerAsyncTasktask=newFileWorkerAsyncTask(this);
task.execute();
}
privatestaticclassFileWorkerAsyncTaskextendsAsyncTask<Void, Void, Void> {
private Service myContextRef;
publicFileWorkerAsyncTask(Service myContextRef) {
this.myContextRef = myContextRef;
}
@Overrideprotected Void doInBackground(Void... params) {
Filefile=newFile(myContextRef.getFilesDir() + "/IP.txt");
// use it ...returnnull;
}
}
}
Solution 2:
I think when you start your service, you should pass String path which getFileDir()
provides as follow.
Intent serviceIntent = newIntent(this,YourService.class);
serviceIntent.putExtra("fileDir", getFileDir());
In your service in onStart
method,
Bundleextras= intent.getExtras();
if(extras == null)
Log.d("Service","null");
else
{
Log.d("Service","not null");
StringfileDir= (String) extras.get("fileDir");
}
Post a Comment for "How To Write To A File In The Internal Storage With An Asynctask In A Service?"