Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creation of AsyncTask taking too much time Android

I am making a network call in an AsyncTask, but the problem i am facing is the amount of time it is taking to start the doInBackground method.

Here is a part of my code:

    button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("Temp:",System.currentTimeMillis()+"");
                new Move().execute();
                /*some other logic
            }
    }

And my AsyncTask is:

    private class Move extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... temp) {
        Log.d("start:",System.currentTimeMillis()+"");
        gson.fromJson(Web.Request.get(some_URL),Void.class);
        Log.d("end:",System.currentTimeMillis()+"");
        return null;
    }
}

These are the logs i got:

           32658-998/com.example.game D/temp:﹕ 1408923006159
           32658-998/com.example.game D/start:﹕ 1408923035163
           32658-998/com.example.game D/end:﹕ 1408923035199

So actually it took almost 29 secs to reach the first line in doInBackground method, where as it took just 36 ms to finish the network call. I tried it many times, the time taken is almost in the same order.

Is it possible to start the AsyncTask immediately? Or is there any other way to solve this problem.(other than a running a simple thread?) Thank you :)

like image 759
Karthik Avatar asked Aug 25 '14 00:08

Karthik


2 Answers

The AsyncTask is waiting for other AsyncTasks to finish running presumably if you have any other tasks running (check if you do).

See here.

Order of execution

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.

like image 54
u3l Avatar answered Nov 18 '22 04:11

u3l


If you have another AsyncTask executing at the same time your AsyncTask is probably waiting for the previous one to finish. However you can force the AsyncTasks to start in multithreads

 Move task = new Move();
 if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
 else
    task.execute();

Hope that helps you, for more information you can read this helpful topic

like image 8
113408 Avatar answered Nov 18 '22 04:11

113408