我想在活动中设置的 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 {
静态 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);
}
}