Creating AsyncTask Takes Too Much Android Time

I am making a network call in AsyncTask, but the problem I am facing is the amount of time it takes to run the doInBackground method.

Here is 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:

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

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

Thus, it took almost 29 seconds to reach the first line in the doInBackground method, since it took only 36 ms to complete the network call. I tried this many times, the time spent is almost in the same order.

Can I run AsyncTask right away? Or is there another way to solve this problem (other than running a simple thread?) Thanks :)

+6
source share
2 answers

AsyncTask expects other AsyncTask finish working, presumably if you have other tasks running (check if you are running).

See here .

Execution order

At the first input, AsyncTasks were executed sequentially on one background thread. Starting with DONUT, this has been changed to a thread pool, allowing multiple tasks to run in parallel. Starting with HONEYCOMB, tasks are executed in a single thread to avoid common application errors caused by parallel execution.

If you really need parallel execution, you can call executeOnExecutor (java.util.concurrent.Executor, Object []) with THREAD_POOL_EXECUTOR.

+8
source

If you have another AsyncTask running at the same time, your AsyncTask is probably waiting for the previous one to complete. However, you can force AsyncTasks to start in multithreaded mode.

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

Hope this helps you, for more information you can read this useful topic.

+6
source

Source: https://habr.com/ru/post/974281/


All Articles