Android AsyncTask 取消时不会停止,为什么? [英] Android AsyncTask won't stop when cancelled, why?

查看:13
本文介绍了Android AsyncTask 取消时不会停止,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 Activity 的 onPause 生命周期事件中关闭的 AsyncTask,因此当有人离开应用程序时它不会运行,但尽管如此,它仍会继续运行.我添加了一些跟踪,这个片段显示了问题.

I've an AsyncTask that I shut down in the Activity's onPause lifecycle event, so it doesn't run when someone leaves the app, but it keeps going despite this. I added some tracing and this snippet shows the problem.

    Trace.d(TAG,"Task state: " + myTask.getStatus() );
    myTask.cancel(true);
    Trace.d(TAG,"Task state: " + myTask.getStatus() );

输出:

Task state: RUNNING
Task state: RUNNING

为什么cancel()方法对任务的状态没有任何影响?我注意到文档说取消方法将尝试"停止任务,但在什么情况下它会失败?该任务肯定正在运行,因为它每十秒输出一次日志输出,并且如您所见,其状态返回为正在运行.

Why is the cancel() method not having any effect on the state of the task? I notice the docs say the cancel method will "attempt" to stop the task, but under what circumstances will it fail? The task is definitely running as it is outputting log output every ten seconds, and as you can see above its status is returned as running.

更新:我添加了跟踪以显示 isCancelled() 状态,并且确实发生了变化.所以调用cancel(true) 是将取消状态从false 更改为true,但显然对Status 没有影响,或者停止线程.

Update: I added tracing to show me the isCancelled() state as well and that DOES change. So the call to cancel(true) is changing the cancelled state from false to true, but apparently having no effect on the Status, or stopping the thread.

推荐答案

我深入挖掘并记得我的线程正在调用一个包含此内容的编写相当糟糕的方法,在我需要取消的线程中生成另一个线程:

I dug deeper and remembered that my thread was calling a rather badly written method containing this, producing another thread inside the one I need to cancel:

public static void haveASleep(int milliseconds)
{
    try
    {
        Thread.sleep(milliseconds);
    }
    catch (InterruptedException ie)
    {
        Trace.w(TAG,"Sleep interrupted");
    }
}

所以发生的事情是AsyncTask线程调用这个方法等待一会,在sleep期间AsyncTask上发生cancel()方法调用,导致线程sleep异常.我的代码无助地捕获并吸收了该异常,而不是使用它来关闭 AsyncTask.

So what was happening was that the AsyncTask thread calls this method to wait a while, and during the sleep the cancel() method call occurs on the AsyncTask, which causes an exception in the thread sleep. My code unhelpfully caught and absorbed that exception, instead of using it to shut down the AsyncTask.

解决办法是在sleep上寻找异常,如果抛出,就悄悄退出线程.该应用程序现在按预期工作,但是...

The solution was to look for an exception on the sleep, and if it is thrown, to quietly exit the thread. The app now works as expected, BUT...

cancel() 方法调用后的状态仍然是RUNNING,但我怀疑这是因为当时它仍在运行,而操作系统尚未将其关闭.我不知道这是否属实,但这是我的最佳估计.

The status immediately after the cancel() method call remains RUNNING, but I suspect this is because at that moment it is still running, and the OS has not yet shut it down. I have no idea if that's true, but that's my best estimate.

这篇关于Android AsyncTask 取消时不会停止,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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