Alarm not getting stopped

前端 未结 3 1596
清歌不尽
清歌不尽 2021-01-07 08:58

I am trying to stop the alarm and checking it whether it stopped or not, but it always returns true means alarm is working. I tried to stop the alarm based on the answer in

相关标签:
3条回答
  • 2021-01-07 09:23

    You are using this code to determine if the alarm is set or not:

    boolean alarmUp = (PendingIntent.getBroadcast(ctx, 1, new Intent(ctx,Alaram_Receiver.class).setAction(Utility.SCHEDULE_ACTION),
        PendingIntent.FLAG_NO_CREATE) != null);
    

    This code relies on the presence of the PendingIntent to determine if the alarm is scheduled or not.

    When you cancel the alarm you do this:

    PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 1,
        intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) ctx
        .getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);
    

    This cancels the alarm, but does not remove the PendingIntent from the system. Since you rely on the presence/absence of the PendingIntent to know if the alarm has been scheduled or not you also need to cancel the PendingIntent so that it will be removed from the system. Do that like this (after you cancel the alarm):

    pendingIntent.cancel();
    
    0 讨论(0)
  • 2021-01-07 09:30

    Here is my code that i am using to cancel the alarm service

    Intent intent = new Intent(this, MyReceiver.class);
             PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
             AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
             alarmManager.cancel(sender);
    
    0 讨论(0)
  • 2021-01-07 09:43

    You have to pass different id for set alarm

    PendingIntent.getBroadcast(ctx, id, intent,PendingIntent.FLAG_UPDATE_CURRENT);
    

    For cancel alarm you have pass sameidthat you used for set.

    PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, id,
            intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) ctx
            .getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(pendingIntent);
    
    0 讨论(0)
提交回复
热议问题