In an existing app I have an activity with an inner class which extends AsyncTask, this looks like the following:
public class Activity_1 extends BaseActivity {
....
new async().execute();
...
public class asyncextends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... progress) { ... }
protected void onPreExecute() { ... }
protected void onPostExecute(String result) { ... }
}
}
Now, I need to call the same doInBackground-method from another activity, but the onPostExecute()
of the this inner class operates on some local UI variables and hence it's not possible to use it from outside the clas.
Is there any way I can call this AsyncTask, and just override the onPostExecute
andonPreExecute
-method, or shall I create yet another inner-class in the other activity, do the same background thing (of course move it to common utility-class or something), etc…?
Best Answer
You can make a separate abstract package private class, extending
AsyncTask
and implementingdoInBackground()
method:And in your activities just inherit from
MyAsyncTask
(new class probably should be private, by the way), implementingonPostExecute()
andonPreExecute()
methods:If
onPreExecute
andonPostExecute
contain some common actions as well, you can apply the following pattern:and use it in your activity as following:
You can also have your
Activity
implementMyAsyncTaskListener
as well:I wrote the code from the head, so it might contain errors, but it should illustrate the idea.