简体   繁体   中英

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 :)

The AsyncTask is waiting for other AsyncTask s 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM