Amrutha
Amrutha

Reputation: 575

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. My requirement is once the notifiation is opened the service should stop. How can I do that?

Please help me in this regard.

Upvotes: 0

Views: 116

Answers (1)

saiful103a
saiful103a

Reputation: 1129

In your service create a BroadcastReciever, in it's onRecieve method you can call stopSelf(), which will stop the service. 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. Once MainActivity open you can send a broadcast to your service which will in turn stop your service. This is the good way to go. Another way is to create a static variable in your 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(); 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.

Upvotes: 1

Related Questions