我可以使用下面的代码创建和取消警报.
我想创建多个警报.闹钟时间来自arraylist.在这个arraylist我想为每个日期创建一个警报.按下取消按钮将仅取消当前警报.我该怎么做?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
buttonCancel.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
// Tell the user about what we did.
Toast.makeText(MainActivity.this,"Cancel!",Toast.LENGTH_LONG).show();
}
});
}
private void setOneTimeAlarm() {
Intent intent = new Intent(this,AReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this,intent,PendingIntent.FLAG_ONE_SHOT);
alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
}
最佳答案
我将以我在其中一个应用程序中创建的方式发布一个示例.
在呼叫闹钟时,您需要发送一个额外的ID,如下所示:
Tmp是具有唯一ID的对象.
Intent intent = new Intent(DisplayActivity.this,AlarmReciever.class);
intent.setData(Uri.parse("timer:"+tmp.getId()));
PendingIntent pendingIntent = PendingIntent.getBroadcast(DisplayActivity.this,1,0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,pendingIntent);
然后用这一行检索id:
Long.parseLong(intent.getData().getSchemeSpecificPart())
取消时只需使用ID创建相同的待处理意图并调用alarmmanager.cancel()
编辑:
要取消用户单击的项目上的特定警报(这里是tmp.getId派上用场的地方)我刚使用此代码,我认为您需要创建相同的pendingIntent才能取消特定的警报.
Intent intent = new Intent(DisplayActivity.this,AlarmReciever.class);
intent.setData(Uri.parse("timer:"+tmp.getId()));
PendingIntent pendingIntent = PendingIntent.getBroadcast(DisplayActivity.this,0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);
AlarmReciever是我的BroadcastReceiver. DisplayActivity是活动本身.
它在AlarmReciever中我有以下代码:
Long.parseLong(intent.getData().getSchemeSpecificPart())