AsyncTask:不调用doInBackground [英] AsyncTask: doInBackground not called

查看:196
本文介绍了AsyncTask:不调用doInBackground的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在AsyncTask上有问题.有时doInBackground()方法不会在onPreExecute()之后调用.

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();

如您所见,我检查Android版本是否为> = HoneyComb,如果是真的,则在Pool Executor中执行任务. 即使具有技巧",有时也不会调用doInBackground().

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?

谢谢

推荐答案

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

Finaly I found a solution to the problem.

我不是使用* AsyncTask.THREAD_POOL_EXECUTOR *执行asyncTask,而是使用较大的corePoolSize和maximumPoolSize实例化了自己的ThreadPoolExecutor:

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

然后...

asyncTask.executeOnExecutor(threadPoolExecutor);

我不知道这是否是一个很好的错误修复程序,但始终会调用doInBackground(). 正如您所说,我想问题是* AsyncTask.THREAD_POOL_EXECUTOR *无法管理我给它的那么多asyncTask.

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.

谢谢你们

这篇关于AsyncTask:不调用doInBackground的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆