Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask's doInBackground starts its execution too late after AsyncTask::execute is called

I wrote an AsyncTask and most of the time there is no delay between its constructor been called and its doInBackground been called (0 ms delay). But whenever contacts syncing is happening at the background, I often experience 1-3 seconds delay between my AsyncTasks's constructor and doInBackground. This delay is unacceptable in my circumstances. I understand that AsyncTask is a background thread and this problem can be solved by using Thread and setting its priority higher. But what I want to found out is, how do I know what's causing my AsyncTask's doInBackground from being called? I used adb shell top -m 10 and the process usage seems quite normal when this issue happened.

Any help is appreciated.

thanks

like image 697
Leo Chen Avatar asked Sep 13 '12 10:09

Leo Chen


2 Answers

I also face this issue for long period, but now it is solved. Use the code below

new AsyncTaskName().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

instead the code

new AsyncTaskName().execute();

it would solve the problem of running doInbackground late.

like image 176
Milan Shukla Avatar answered Sep 28 '22 05:09

Milan Shukla


We generally don't bother about task scheduling by the jvm. And infact we need not to bother also.

If something needs to be done as quick as possible in your application do it in the constructor itself or use onPre of Asynctask (Remember it execute on UI thread).

But i agree there is something fishy in the doInBackgroud calling in Android AsyncTask i itself had witnessed the doInbackground didn't get called after onPre. You can google this also. many people had faced it. I moved to use Traditional Thread.

I wrote my own Asynctask using Traditional thread at core and to mimic onPre and onPost i used Handler. You can go for that option also.

like image 45
Rohit Sharma Avatar answered Sep 28 '22 06:09

Rohit Sharma