Your code makes no sense. You have to keep in mind three basic things:
- All alarms are linked to the specific application.
- Alarms functionality is based on the pending intents.
- 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…