Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android AsyncTask: what is difference between execute() and get()?

Should I write smth like that

return task.exec(session, state).get(json_timeout, TimeUnit.MILLISECONDS);

Or I can do like this

task.exec(session, state, result);
return result;

A have already read all documentation that I found, but failed to find an answer. My bad...

like image 998
Pavel Vyazankin Avatar asked Dec 25 '22 21:12

Pavel Vyazankin


2 Answers

Do not use get(). It will block the ui thread until asynctask finishes execution which no longer makes it asynchronous.

Use execute and to invoke asynctask

new task().exec(session, state, result);

Also you can pass the params to the constructor of asynctask or to doInbackground()

http://developer.android.com/reference/android/os/AsyncTask.html

public final Result get ()

Added in API level 3
Waits if necessary for the computation to complete, and then retrieves its result.

You can make your asynctask an inner class of your activity class and update ui in onPostExecute.

If asynctask is in a different file then you can use interface.

How do I return a boolean from AsyncTask?

like image 180
Raghunandan Avatar answered Mar 07 '23 02:03

Raghunandan


AsyncTask#get() will block the calling thread.

AsyncTask#execute() will run in a separate thread and deliver the Result in onPostExecute(...).

I would recommend against using the get() method except in special cases like testing. The whole purpose of the AsyncTask is to execute some long-running operation in doInBackground() then handle the result once it's finished.

One example of normal AsyncTask execution would look like:

Task task = new Task(){
    @Override
    protected void onPostExecute(Result result) {
        super.onPostExecute(result);
        //handle your result here
    }
};
task.execute();
like image 31
James McCracken Avatar answered Mar 07 '23 02:03

James McCracken