Search code examples
androidservicealarmmanager

Stop AlarmManager from Service but created in Activity


I create an AlarmManager following way. After a specific time the service stops with stopSelf() but the alarmmanager starts the Service again. How can I stop the AlarmManager inside the Service? The Activity is't running anymore, I have to do it inside the Service.

Activity which starts the Service periodically with AlarmManager:

Intent i=new Intent(this, AppService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 

if((tb_runBG.isChecked()))
{    
    alarmManager.cancel(pi);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 *update_time, pi);                              
}
else
  {    
    // From Activity it's no problem to stop the AlarmManager   
    alarmManager.cancel(pi);
    stopService(new Intent(this, AppService.class));                     
  }

Service in which I try to stop the AlarmManager:

Intent i=new Intent(this, volumeActivity.class);                      
PendingIntent pi=PendingIntent.getActivity(this, 0, i, 0);
// Her I should get the getSystemService from the Activity, but how??
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Following unfortunately not working ...
alarmManager.cancel(pi);
stopSelf(); 

Unfortunately it's not working. The Servive stops, but its called again by the AlarmManager ...

EDIT:

Following also not Working:

AlarmManager alarmManager = (AlarmManager) this.getBaseContext().getSystemService(Context.ALARM_SERVICE); 

or

AlarmManager alarmManager = (AlarmManager) this.getApplicationContext().getSystemService(Context.ALARM_SERVICE);  

Solution

  • I guess the PendingIntent should be same in the cases when you are setting an alarm and when you are cancelling an alarm. In your case, the second pending intent is not same as the first one. Can you once try the following in your cancel code?

        PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
    

    Edit: Just noticed, your intents are not same either. Is it deliberate?