I have a problem with the AsyncTask
. Sometimes the doInBackground()
method is not called after onPreExecute()
.
I know this question was asked several times but the given answers don't work for me.
Here is a part of my code:
AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>(){
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("AsyncTask", "onPreExecute");
}
@Override
protected Void doInBackground(Void... params) {
Log.e("AsyncTask", "doInBackground");
return null;
}
protected void onPostExecute(Void result) {
Log.e("AsyncTask", "onPostExecute");
};
};
if(Build.VERSION.SDK_INT >= 11)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else
asyncTask.execute();
As you can see, I check if the Android version is >= HoneyComb and execute the task in the Pool Executor if it's true.
Even with that "trick" sometimes doInBackground()
is not called.
Does somebody have the same issue or knows how what's the problem?
Thank you
Finaly I found a solution to the problem.
Instead of execute the asyncTask with the *AsyncTask.THREAD_POOL_EXECUTOR*, I instanciate my own ThreadPoolExecutor with a large corePoolSize and maximumPoolSize:
int corePoolSize = 60;
int maximumPoolSize = 80;
int keepAliveTime = 10;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(maximumPoolSize);
Executor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue);
And ...
asyncTask.executeOnExecutor(threadPoolExecutor);
I don't know if this is a good bugfix but with this, doInBackground() is always called. As you said, I supose that the problem was that *AsyncTask.THREAD_POOL_EXECUTOR* could not manage as much asyncTasks as I gave to it.
Thank you guys
It happened to me one time because some of my tasks were blocked in the doInBackground()
(which is obviously impossible with the code sample you pasted).
The default pool size on Android for the THREAD_POOL_EXECUTOR was 5 the last time I have checked. So if you execute more than 5 tasks at the same time the next ones will wait until a task is finished.
It's the only case I known to prevent a doInBackground()
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With