简体   繁体   English

如何在Android中停止闹钟服务?

[英]How to stop an alarm service in android?

I have gone through the link and executed the code. 我已经通过链接并执行了代码。 It is working fine. 一切正常。 But now I need to stop the service in that. 但是现在我需要停止该服务。 How can I do that? 我怎样才能做到这一点? I overided stopservice method in MyAlarmService but i didnt get where to call stop service. 我在MyAlarmService中覆盖了stopservice方法,但是我没有在哪里调用停止服务。 My requirement is once the notifiation is opened the service should stop. 我的要求是,一旦打开通知,服务应停止。 How can I do that? 我怎样才能做到这一点?

Please help me in this regard. 请在这方面帮助我。

In your service create a BroadcastReciever, in it's onRecieve method you can call stopSelf(), which will stop the service. 在您的服务中创建一个BroadcastReciever,在它的onRecieve方法中,您可以调用stopSelf(),这将停止该服务。 Now you need to send a broadcast event so that your service can catch it.You can do that via your pending intent. 现在您需要发送一个广播事件,以便您的服务可以捕获它。您可以通过未决的意图来做到这一点。 In the tutorial you are following, you can see that MainActivity will be opened as soon as user hits the notification. 在您遵循的教程中,您可以看到用户点击通知后便会立即打开MainActivity。 Once MainActivity open you can send a broadcast to your service which will in turn stop your service. 一旦MainActivity打开,您就可以向您的服务发送广播,这将进而停止您的服务。 This is the good way to go. 这是个好方法。 Another way is to create a static variable in your Service: 另一种方法是在Service中创建一个静态变量:

  public class MyAlarmService extends Service { private static MyAlarmService mMyAlarmService; public static MyAlarmService getInstace(){ return mMyAlarmService; } @Override public void onCreate() { mMyAlarmService = this; super.onCreate(); } } 

When user taps on a notification in your MainActivity you can call MyAlarmService.getInstance().stopSelf(); 当用户在MainActivity中点击通知时,可以调用MyAlarmService.getInstance()。stopSelf();。 Of course you have to do some null-checking first.Though it's not a best way to go but it should do the trick. 当然,您必须先进行一些null检查,尽管这不是最佳方法,但应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM