AsyncTask:未调用doInBackground

Val*_*tin 11 android android-asynctask

我有一个问题AsyncTask.有时该doInBackground()方法不会被调用onPreExecute().

我知道这个问题被多次询问,但给定的答案对我不起作用.

这是我的代码的一部分:

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();
Run Code Online (Sandbox Code Playgroud)

如您所见,我检查Android版本是否=> HoneyComb并在池执行器中执行任务,如果它是真的.即使有这种"技巧",有时doInBackground()也不会被称为.

有人有同样的问题或知道问题是什么?

谢谢

Val*_*tin 37

最后,我找到了解决问题的方法.

我没有使用*AsyncTask.THREAD_POOL_EXECUTOR*执行asyncTask,而是使用大型corePoolSize和maximumPoolSize实现我自己的ThreadPoolExecutor:

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);
Run Code Online (Sandbox Code Playgroud)

而......

asyncTask.executeOnExecutor(threadPoolExecutor);
Run Code Online (Sandbox Code Playgroud)

我不知道这是一个很好的错误修正,但有了这个,总是调用doInBackground().正如你所说,我supose的问题是,因为我给它*AsyncTask.THREAD_POOL_EXECUTOR*无法管理尽可能多asyncTasks.

感谢你们