Home:ALL Converter>How to write to a file in the internal storage with an asynctask in a service?

How to write to a file in the internal storage with an asynctask in a service?

Ask Time:2013-09-05T19:58:55         Author:Readdeo

Json Formatter

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");

Author:Readdeo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/18635724/how-to-write-to-a-file-in-the-internal-storage-with-an-asynctask-in-a-service
gunar :

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.\n\nSomething like:\n\nFile file = new File(myContextRef.getFilesDir() + \"/IP.txt\");\n\n\nWhen you're creating the AsyncTask pass a reference of current Service (I suppose you're creating the AsyncTaskObject from Service):\n\nimport java.io.File;\n\nimport android.app.Service;\nimport android.content.Intent;\nimport android.os.AsyncTask;\nimport android.os.IBinder;\n\npublic class MyService extends Service {\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n protected void useFileAsyncTask() {\n FileWorkerAsyncTask task = new FileWorkerAsyncTask(this);\n task.execute();\n }\n\n private static class FileWorkerAsyncTask extends AsyncTask<Void, Void, Void> {\n\n private Service myContextRef;\n\n public FileWorkerAsyncTask(Service myContextRef) {\n this.myContextRef = myContextRef;\n }\n\n @Override\n protected Void doInBackground(Void... params) {\n File file = new File(myContextRef.getFilesDir() + \"/IP.txt\");\n // use it ...\n return null;\n }\n }\n}\n",
2013-09-05T12:05:30
yy