强制的IntentService立即停止 [英] Forcing an IntentService to stop immediately

查看:695
本文介绍了强制的IntentService立即停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是从活动开始,一个IntentService,我希望能够从该活动立即停止服务,在活动一个取消按钮。一旦这个取消按钮是pressed,我希望该服务停止执行的code线。

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.

我发现了一些类似这样的问题(即此处, <一href="http://stackoverflow.com/questions/7173306/manually-ending-the-intentservice-worker-thread">here, 这里,的此处),但没有好的答案。 Activity.stopService() Service.stopSelf()执行 Service.onDestroy() 方法立即但随后让 onHandleIntent的code()销毁服务之前完成所有的方式通过。

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()法切换服务的布尔成员变量,然后让的几乎每一个线code。在 onHandleIntent()裹在自己的如果条款看这个变量。这是一个可怕的方式来写code。

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?

推荐答案

要immediatelly停止THEAD /过程始终是一个肮脏的事情。但是,它应该是罚款,如果你的服务是无状态的。

To stop a thead/process immediatelly is always 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天全站免登陆