从活动中停止IntentService [英] Stopping an IntentService from an activity

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

问题描述

我有一个IntentSerivce有时在后台运行,在某些情况下它可能是一个相当长的运行过程.我为用户提供了一个退出应用程序的选项,该应用程序基本上只是停止并轮询,而忽略任何GCM推送通知.但是,如果出现了推送通知,而IntentService则需要一段时间才能完成其必须执行的工作(从服务器获取信息,并在需要时向用户发送通知,例如收到新消息或类似的消息).

这是问题所在,如果用户选择在intentservice仍在运行时退出"应用程序,他们仍会收到我不想要的通知.我知道该服务有stopSelf()方法,但是当我知道用户通过菜单按钮退出"该应用程序时,需要在活动中停止该方法.将另一个intent发送到该服务不起作用,因为意图被排队,并且在我的活动中调用context.stopService(intent);也不起作用,所以我还能怎么停止它?

解决方案

您是否要将新的Intent传递给stopService(Intent)startService(Intent)中使用的原始Intent.传递原始意图将停止服务.

无法使用Handler将服务传递给Message.让IntentService实现Handler.Callback接口并在Activity中创建一个新的Handler(Handler.Callback),并将您的IntentService作为回调传递.然后,在IntentService中实现onHandleMessage()来调用stopSelf(),并让您的Activity在要停止时向其传递消息.

I have an IntentSerivce that runs in the background sometimes and it can be quite a long running process in certain instances. I give an option for the user to quit the application which basically just stops and polling and ignores any GCM push notifications. But if a push notification came in and the IntentService is taking a while to finish doing what it has to (gets information from a server and sends a notification to the user if needed, like a new message arrived or something).

Here is the problem, if the user elects to "Quit" the app while the intentservice is still running they will still get the notification which I do not want. I know that there is the stopSelf() method for the service but I need to stop it in an activity when I know the user "Quit" the application via a menu button. Sending another intent to the service does not work since the intents get queued up and calling context.stopService(intent); in my activity does not work either so how else can I stop it?

解决方案

Are you passing a new Intent into stopService(Intent) or the original one used in startService(Intent). Passing the original Intent should stop the service.

Failing that you could use a Handler to pass the service a Message. Have the IntentService implement the Handler.Callback interface and create a new Handler(Handler.Callback) in your Activity, passing your IntentService as callback. Then implement the onHandleMessage() in your IntentService to call stopSelf() and have your Activity pass a message to it when you want it to stop.

这篇关于从活动中停止IntentService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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