42

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)

  1. Is this proper use of AsyncTask ?
  2. If so can I extend AsyncTask instead ?
  3. What is the difference between extending AsyncTask and AsyncTask<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

Rami
  • 2,098
  • 5
  • 25
  • 37
  • "What is the difference between extending AsyncTask and AsyncTask" <- That statement couldn't be less clear, could you be more specific? – devunwired Jun 25 '12 at 18:00
  • 2
    sorry apparently <> can't be shown. I edited the question. – Rami Jun 25 '12 at 18:06

4 Answers4

57

The AsyncTask class 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:

    new AsyncTask<Integer, Void, Void>(){
        @Override
        protected Void doInBackground(Integer... params) {
            // **Code**
            return null;
        }
    }.execute(1, 2, 3, 4, 5);

It will execute whatever you put in doInBackground on a background thread with the given parameters. Likewise, you can simply use Void and 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 Void object is a Java object just like anything else. You're not using Void, so what you use in it's place doesn't matter. It's just the AsyncTask contract requires three class types to be passed in, and by default they're Object which is the baseline class of everything.

DeeV
  • 35,865
  • 9
  • 108
  • 95
  • And how long is new AsyncTask object's lifetime, when garbage collector can collect it? – mes Jul 17 '14 at 08:16
  • @mes The AsyncTask will live as long as doInBackground runs. As soon as doInBackground finishes and onCancel or onPostExecute is called, then the object is subject for garbage collection. When the garbage collector actually removes the object from memory is up to the JVM. – DeeV Jul 17 '14 at 13:00
16

(I have no use in performing any UI in this class)

Then just use the normal Thread class rather than using AsyncTask class which is designed for dealing with UI changes during the thread's life time:

Runnable r = new Runnable()
{
    @Override
    public void run()
    {
        // your code here
    }
};

Thread t = new Thread(r);
t.start();
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • 3
    This is correct. AsyncTask is just a wrapped thread to make it easier to program background tasks that interact with the UI. If the OP is not dealing with UI, then it makes sense to just deal directly with threads. – telkins Jun 25 '12 at 18:11
  • 1
    Yes, generics are nice, but AsyncTask is not what Rami needs based on what was posted. If generics are wanted, then something like http://stackoverflow.com/questions/1659986/java-parameterized-runnable could be implemented or AsyncTask could be used. – telkins Jun 25 '12 at 19:00
  • 1
    This answer and @trevor-e are incorrect. Spawning new threads, in an application, is an incredibly expensive way push a task off the UI thread. It is much better to use an AsyncTask. AsyncTasks are, efficiently, run on a ThreadPoolExectutor and not "just a wrapped thread". – G. Blake Meike Jul 12 '18 at 17:11
  • 1
    @G.BlakeMeike I disagree and believe you are incorrect. All AsyncTasks share a thread pool under the hood, why would you want to potentially block that pool with a non-UI related task? Note that I never specified _how_ to deal directly with threads, rather that it makes no sense to use an API designed to post back to the main UI thread for something that doesn't involve the UI. You could just as easily create a separate thread pool to save on spawning threads, that is not unique to AsyncTask. – telkins Jul 19 '18 at 00:37
  • @trevor-e You state: "AsyncTask is just a wrapped thread" Since there is so much misunderstanding on the subject, I feel it important to be clear that that is simply not true. ... and, btw, you can post AsyncTasks to their native thread pool, or any other thread pool that you create, should you decide that there is a reason to do that. – G. Blake Meike Jul 22 '18 at 22:33
3

Is this proper use of AsyncTask ?

You don't said what is your goal. But AsyncTask is generally used for long tasks and updating UI during work exactly to notify some progress change of some long work. It's also very efficient, type-safe tool and more complex than Handler for example.

What is the difference between extending AsyncTask and AsyncTask

AsyncTask is generic type and you should use generics with them is code more faster, more type-safe.

I have no use in performing any UI

So you rather can use Handler or classical Runnable interface and you can work only with worker threads basically.


Note: Generally, using of generics types makes code faster, most type-safe. Also next advantage is strong type checking at compile source code, restrictions of explicit conversions etc.

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
  • 5
    Actually as per the documentation AsyncTask should be used for shorter tasks. Seen the "Class Overview" section at http://developer.android.com/reference/android/os/AsyncTask.html – Mafro34 Nov 19 '13 at 10:23
0
  1. is this proper use of asynctask?

I don't think there is any proper use. You can use asynctask to perform intensive operations on background thread and publish result, updates on main thread. It's not mandatory that you must publish result or progress. That's given to you. Your decision.

But for your network operations, you can use thread also. But later you decided to publish result and progress on main thread, Asynctask will help you in a simple way.

Threads don't.

Asynctask uses generic datatypes as parameters. You must provide it. If you don't want to provide or accept any data from asyctask. You can use Void type,

just like given below

class MessagePooling extends AsyncTask<Void,Void,Void>

It means asynctask will get no parameters, give you no progress or result.

For more about asynctask: http://androidride.com/beginners-guide-asynctask-android-tutorial-example/