Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages/disadvantages on passing arguments to the AsyncTask constructor?

I am using AsyncTask and wondering what are the implications of passing the arguments to the constructor instead of passing them directly on the execute() call to the doInBackground(...) method, for example:

Call:

new SomeTask(bitmap, integer, "somestring").execute();

Class:

public class SomeTask extends AsyncTask<Void, Void, String> {
private String string;
private Bitmap image;
private int integer;

public SomeTask (Bitmap bmp, int someint, String s){
    this.image = bmp;
    this.string = s;
    this.integer = someint;
}

protected String doInBackground(Void... params) {       
    // whatever
    return "string";
}

@Override
protected void onPostExecute(String result){
    // whatever
}

}

What are the advantages/disadvantages regarding design, elegance, reuse and performance?

Thank you.

like image 246
MobileCushion Avatar asked Sep 21 '11 10:09

MobileCushion


People also ask

What is the limitations of AsyncTask?

The modern AsyncTask is limited to 128 concurrent tasks, with an additional queue of 10 tasks (if supporting Android 1.5, it's a limit of ten tasks at a time, with a maximum queue of 10 tasks). That means that if you queue up more than 138 tasks before they can complete, your app will crash.

What are the problems in AsyncTask?

In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.

What is difference between service thread and AsyncTask?

service is like activity long time consuming task but Async task allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.

What happens to AsyncTask if activity is destroyed?

If you start an AsyncTask inside an Activity and you rotate the device, the Activity will be destroyed and a new instance will be created. But the AsyncTask will not die. It will go on living until it completes. And when it completes, the AsyncTask won't update the UI of the new Activity.


1 Answers

What are the advantages/disadvantages regarding design, ellegance, reuse and performance??

Use parameters to execute() if you will have an arbitrary number of the same type (e.g., several URLs as Strings that you want the task to download).

Use constructor parameters if you will have several parameters of distinct types, so you can take advantage of Java's compile-time type safety.

If you will have just one object to pass in (or none), both approaches are pretty much equivalent.

like image 121
CommonsWare Avatar answered Oct 23 '22 08:10

CommonsWare