我想在活动中设置的BroadcastReceiver的onReceive方法中停止或取消重复警报。我应该在哪里调用cancel()方法,如何在BroadCastReceiver的OnReceive方法中获取alarmManager的实例。
以下是代码段
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
Intent intent1 = new Intent(this, MyBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE)
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), 60*1000, pendingIntent);
}
公共类MyBroadcastReceiver扩展了BroadcastReceiver {
static int id;
@Override
public void onReceive(Context context, Intent intent) {
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
id=id+1;
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher,
"A new notification", System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent1 = new Intent(context, Repeat.class);
PendingIntent activity = PendingIntent.getActivity(context, id, intent1,
PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context, "This is the title",
"Notified", activity);
notification.number += 1;
notificationManager.notify(id, notification);
String as = Context.ALARM_SERVICE;
PendingIntent sender = PendingIntent.getBroadcast(context, 1234567, intent, 0);
AlarmManager amg = (AlarmManager) context.getSystemService(as);
amg.cancel(sender);
}
}
答案 0 :(得分:0)
如果要取消闹钟,可以使用以下代码。 (我没有测试过这个,但我做了类似的事情来取消NotificationService)
String as = Context.ALARM_SERVICE;
AlarmManager amg = (AlarmManager) this.getSystemService(as);
PendingIntent myIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent1, 0);
amg.cancel(myIntent);