Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask not running asynchronously

The following were supposed to be the same if I am not mistaking.
Using AsyncTask:

private class GetDataTask extends AsyncTask<String, Void, String>{

    @Override
    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(String... params) {
        return NetConnection.getRecordData(mUserId, mUserPassword);
    }

    @Override
    protected void onPostExecute(String result) {
        parseJson(result);
    }
}

Using a Thread:

    new Thread( new Runnable() {

        @Override
        public void run() {
            String res = NetConnection. getRecordData(mUserId, mUserPassword);
            parseJson(res);

        }
    }).start();

But when uploading a file, the AsyncTask runs synchronously while the Thread run asynchronously(in parallel).
Why is so? Why AsyncTask behaves like this? Isn't AsyncTask supposed to run asynchronously?
I am little confused so I need your help.
This is how I invoke the GetDataTask:

new GetDataTask().execute()

I prefer using AsyncTask but it is not doing the job for me. Please refer to my early question for more details

like image 799
Lazy Ninja Avatar asked Mar 18 '13 07:03

Lazy Ninja


1 Answers

As of 4.x calling 2 AsyncTasks will cause them to be executed serially.

One way to fix this is using the following code

if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
  myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else {
  myTask.execute();
}

You can read more at: http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html

like image 194
David Olsson Avatar answered Oct 21 '22 14:10

David Olsson