In my android app I am performing some operations in the doInBackground by extending AsyncTask<Void, Void, Void> class. (I have no use in performing any UI in this class)
- Is this proper use of AsyncTask ?
- If so can I extend AsyncTask instead ?
- What is the difference between extending
AsyncTaskandAsyncTask<Void, Void, Void>
Code example:
public class MessagePooling extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... params)
{
while (!isCancelled())
{
//Getting data from server
SystemClock.sleep(1000);
}
return null;
}
}
Or:
public class MessagePooling extends AsyncTask
{
@Override
protected Object doInBackground(Object... params)
{
while (!isCancelled())
{
//Getting data from server
SystemClock.sleep(1000);
}
return null;
}
}
Thanks
The
AsyncTaskclass can be thought of as a very convenient threading mechanism. It gives you a few tools that you can use that simple Java threads simply don’t have such as on cancel cleanup operations. You don’t have to do any UI in the background. You could simply execute one by writing one as an anonymous class like this:It will execute whatever you put in
doInBackgroundon a background thread with the given parameters. Likewise, you can simply useVoidand execute with no parameters.The only advantage I could think of executing a thread this way would be to aid in future maintenance. There might be a case where you want to modify certain things that are required to be on the UI thread, in which case you would override the other methods. Other cases would be you simply don’t do the action enough to justify writing out another class, so just create one on the fly and be done with it.
EDIT:
To answer #3: they’re effectively the same. The
Voidobject is a Java object just like anything else. You’re not usingVoid, so what you use in it’s place doesn’t matter. It’s just theAsyncTaskcontract requires three class types to be passed in, and by default they’reObjectwhich is the baseline class of everything.