cancel repeating alarm at specific time

后端 未结 1 945
半阙折子戏
半阙折子戏 2020-12-18 12:08

I\'m looking to cancel 2 repeating alarms at a specific time but the app currently decides to call the cancel as soon as you create the alarms. For example if you set the th

相关标签:
1条回答
  • 2020-12-18 12:48

    Your code makes no sense. You have to keep in mind three basic things:

    1. All alarms are linked to the specific application.
    2. Alarms functionality is based on the pending intents.
    3. Cancellation can be done my matching to specific Intent.

    Considering that, you can implement the following solution.

    Create basic alarm as usual:

    Intent myIntent = new Intent(this, Target.class);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    

    Create another alarm, which will be responsible for cancellation and put pendingIntent from the 1st alarm to it:

    Intent cancellationIntent = new Intent(this, CancelAlarmBroadcastReceiver.class);
    cancellationIntent.putExtra("key", pendingIntent);
    PendingIntent cancellationPendingIntent = PendingIntent.getBroadcast(this, 0, cancellationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    am.set(AlarmManager.RTC_WAKEUP, time, cancellationPendingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    

    Where CancelAlarmBroadcastReceiver is the following:

    public class CancelAlarmBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            PendingIntent pendingIntent = intent.getParcelableExtra("key");
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.cancel(pendingIntent);
        }
    }
    

    I didn't check it, but I think it should work.

    0 讨论(0)
提交回复
热议问题