1

I'm trying to refactor one of my activities. I have a very big private AsyncTask class, which I want to put in a separate class. The AsyncTask itself should also update the UI when finished, so I must provide the application context for that class.

Now which of those two is the better approach: Just create the class as a task?

public class MyCustomTask extends AsyncTask

Use with:

 new MyCustomTask().execute();

Or create an Actitvity that itself launches the task, and call this Actitivy by Intent?

public class MyCustomActivity extends Activity {
  onCreate() {
    new MyCustomTask().execute();
  }

  private class MyCustomTask extends AsyncTask<..>();
}

Use with:

Intent intent = new Intent(this, MyCustomActivity.class);
membersound
  • 81,582
  • 193
  • 585
  • 1,120

4 Answers4

3

If you have a separated AsyncTask and need to do UI manipulation on postExecute, there are 3 ways to execute it:

  1. override it in your Activity. In the sub-class only add UI manipulation code.

  2. create a interface and use it as a listener. see here

  3. pass your activity as a paramter to the AsyncTask. see here

For 2 and 3 you want to check if the Activity still alive in postExecute().

Community
  • 1
  • 1
Xi 张熹
  • 10,492
  • 18
  • 58
  • 86
2

Here is how I do ASyncTask stuff in my Activities:

public class MyClass extends Activity {

     @Override
     public void onClick(View v) {
          MyNewThread thread = new MyNewThread();
          thread.execute();
     }

     private class MyNewThread extends ASyncTask<Void, Void, Void> {
          //Code goes here
     }

}

Very pseudo-code but you get the idea, it's just a inner private class for the activity. Now if this exact thread is something you will be running in multiple activities, then it might be worth making it its own class. But if you're just doing this here, this implementation is fine. Either way though, don't make it an activity, its just a regular class that extends ASyncTask.

JMRboosties
  • 15,500
  • 20
  • 76
  • 116
1

There's no reason to create a separate Activity purely to launch the AsyncTask. Just create it as a separate class and pass in a Context if necessary. Just make sure you don't leak it.

kabuko
  • 36,028
  • 10
  • 80
  • 93
1

Just remain the same if the AsyncTask interacts with the Activity, otherwise create a separate one. The advantage to use AsyncTask as an inner class is that this class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

kebo
  • 56
  • 3