4

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...

Pavel Vyazankin
  • 1,470
  • 6
  • 18
  • 27

2 Answers2

6

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?

Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
4

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();
James McCracken
  • 15,488
  • 5
  • 54
  • 62