Hick
Hick

Reputation: 36414

Is this the best way to implement AsyncTask? Or are there better ways?

I am trying to write a AsyncTask generic package. Till now, what I've done is call one activity from another send the instance in the Intent to that Activity. This activity is part of the AsyncTask which calls the AsyncLoader.execute() file. I am doing this so that I don't lose any data that the parent Activity sets on the layout.

The other way to do it would be to call the Intent and return the data from the AsyncActivity to the parent Activity. But, both of these methods are slower than implementing the AsyncTask in the parent activity.

But, that clutters up the code. Thus, is there a better way of implementing it?

Upvotes: 2

Views: 633

Answers (1)

James Goodwin
James Goodwin

Reputation: 7406

It sounds like your tight-coupling between the activity and the AsyncTask is causing you issues that you're trying to overcome with a weird workaround.

In my experience the best way to design activities that need an AsyncTask is:

  • Keep your AsyncTask out of your activity, i.e. make a separate class that extends AsyncTask. This allows you to reuse the AsyncTask between multiple activities and make it easier to test.
  • If you need to return data back to your activity, use the listener and implement the listener on your activity. Then pass your listener to a class that creates the AsyncTask.

Passing of data between intents should be kept to a minimum, if you need to reuse the same AsyncTask from a separate activity you should follow the steps above and execute the task again. If you're going to be calling this through the lifecycle of the app, then consider using a service instead.

Upvotes: 3

Related Questions