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.
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.
In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With