问题
I am using a Boot receiver to fire AlarmManager,so that it repeats it's task every minute. I'd like the user to have in app option to enable/disable action that is done in every repeat of AlarmManager. So far I only used only a lame solution. I set user's preference in SharedPreferences and in every repeat of AlarmManager I check for user's preference in SharedPreferences and based on this preference the functionality is either executed or ignored.
So far to my best knowledge, there is no way to completely destroy AlarmManager from within itself. but I might be wrong.
Also, since boot receiver is registered in AndroidManifest.xml and a BroadcastReceiver only really exists when onReceive is called, there is probably no way of getting a reference to AlarmManager object, so that I could cancel the alarm from the outside with AlarmManager.cancel. But I might be wrong about all this.
So I'd like to ask, if I am mistaken about all this, or if there is some way to completely destroy/cancel AlarmManager started on Boot(from inside the AlaramManager, or outside, doesn't matter). Any ideas? Thanks in advance
回答1:
You can cancel the alarm any time by using the same Pending Intent.
Intent intent = new Intent(show.this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(show.this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
<Alarm_Manager_Object>.cancel(pendingIntent);
来源:https://stackoverflow.com/questions/8268657/android-is-there-a-way-to-stop-alarmreceiver-fired-in-bootreceiver