在停止服务时取消AsyncTask

时间:2014-07-03 09:43:06

标签: android service android-asynctask

我正在使用

Intent I=new  Intent(Myactivity.this,MyService.class);

意图启动和停止服务。我在此服务中有一个 AsycTask ,在任务完成或应用程序关闭之前不会停止。要在停止服务时停止 Asynctask ,我尝试将 onDestroyed 方法调用为

@Override
public void onDestroy() {
    if (task!=null) {
        if(!task.isCancelled()) {
            task.onCancelled();
            task.cancel(true);
        }
    }
    isRunning=false;
    System.out.println("service destroyed");
    super.onDestroy();
    stopSelf();
}

(我认为没有触发,因为在调用 stopService(I)后甚至当任务完成时,不会打印“ service destroyed ”消息。 接下来我尝试将 Asyctask 类静态化,并从 Myactivity 调用取消(true)方法,这也没有帮助。任何有用的建议apreciated

1 个答案:

答案 0 :(得分:1)

如果将AsyncTask设置为取消,则需要在AsyncTask中进行检查。检查here the AsyncTask documentation, topic "Usage"

// at one point in your doDownload() method check for cancel state
if (isCancelled()) {
    // do a break or just return or what ever you need for a clean exit
}

我不确定你是如何完全停止服务的,但基本上是that should work

相关问题