如何通过活动中的取消按钮强制IntentService立即停止? [英] How to force an IntentService to stop immediately with a cancel button from an Activity?

查看:437
本文介绍了如何通过活动中的取消按钮强制IntentService立即停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从Activity启动的IntentService,我希望能够通过该活动中的取消"按钮立即从该活动中停止该服务.按下该取消"按钮后,我希望该服务停止执行代码行.

I have an IntentService that is started from an Activity and I would like to be able to stop the service immediately from the activity with a "cancel" button in the activity. As soon as that "cancel" button is pressed, I want the service to stop executing lines of code.

我发现了许多与此类似的问题(例如,此处此处此处),但没有好的答案. Activity.stopService()Service.stopSelf()立即执行Service.onDestroy()方法,但是在销毁服务之前,先让onHandleIntent()中的代码完全完成.

I've found a number of questions similar to this (i.e. here, here, here, here), but no good answers. Activity.stopService() and Service.stopSelf() execute the Service.onDestroy() method immediately but then let the code in onHandleIntent() finish all the way through before destroying the service.

由于显然没有保证立即终止服务线程的方法,因此我可以找到唯一推荐的解决方案(此处)是在服务中具有一个布尔成员变量,可以在onDestroy()方法中进行切换,然后将onHandleIntent()中的代码的每一行都包装在其中自己的"if"子句查看该变量.那是编写代码的糟糕方法.

Since there is apparently no guaranteed way to terminate the service's thread immediately, the only recommended solution I can find (here) is to have a boolean member variable in the service that can be switched in the onDestroy() method, and then have just about every line of the code in onHandleIntent() wrapped in its own "if" clause looking at that variable. That's an awful way to write code.

有人知道在IntentService中执行此操作的更好方法吗?

Does anybody know of a better way to do this in an IntentService?

推荐答案

立即停止线程或进程通常是一件肮脏的事.但是,如果您的服务是无状态的,那应该没问题.

Stopping a thread or a process immediately is often a dirty thing. However, it should be fine if your service is stateless.

在清单中将服务声明为一个单独的进程:

Declare the service as a separate process in the manifest:

<service
     android:process=":service"
     ...

当您想要停止执行时,只需终止该进程即可:

And when you want to stop its execution, just kill that process:

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningAppProcesses = am.getRunningAppProcesses();

Iterator<RunningAppProcessInfo> iter = runningAppProcesses.iterator();

while(iter.hasNext()){
    RunningAppProcessInfo next = iter.next();

    String pricessName = getPackageName() + ":service";

    if(next.processName.equals(pricessName)){
        Process.killProcess(next.pid);
        break;
    }
}

这篇关于如何通过活动中的取消按钮强制IntentService立即停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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