Search code examples
androidandroid-servicealarmmanager

How to stop service using AlarmManager


I have an alarm manager that runs a service repeatedly every minute. I want to stop the alarm manager using a button.

The alarm manager stops when I am inside the app but when it comes out of the app and I want to stop the clock again, it will not stop as there is no pending intent in memory. Using a new pending intent, the previous pending intent will not stop, even though I am using the same id.

btnStart.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {

    Intent intent = new Intent(G.context, MyService.class);
    intent.setAction("1020");
     pendingIntent = PendingIntent.getService(G.context, 1020, intent, 0);
    G.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 2000, pendingIntent);

  }
});//for start button  alarm manager

btnStop.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    Intent intent = new Intent(G.context, MyService.class);
    intent.setAction("1020");
    PendingIntent alarmIntent = PendingIntent.getBroadcast(G.context,  1020, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmIntent.cancel();
    G.alarmManager.cancel(alarmIntent);

  }
});//for stop button alarm manager

Solution

  • You can make pendingIntent global and use the same to set/stop as in

    Intent intent = new Intent(G.context, MyService.class);
    intent.setAction("1020");
    pendingIntent = PendingIntent.getService(G.context, 1020, intent, 0);
    
    btnStart.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        G.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 2000, pendingIntent);
    
      }
    });
    
    btnStop.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        pendingIntent.cancel();
        G.alarmManager.cancel(pendingIntent);
    
      }
    });