Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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");
like image 268
Readdeo Avatar asked Nov 02 '22 15:11

Readdeo


1 Answers

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;
        }
    }
}
like image 81
gunar Avatar answered Nov 09 '22 10:11

gunar