在我的应用程序中,我使用了多个“警报管理器”,它们都工作正常。现在,我的应用中还需要两件事:
为每个alarmManager设置一个ID,以便我可以在广播接收器中识别此警报
使用此ID稍后取消警报
我的设置闹钟代码
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, h1);
cal1.set(Calendar.MINUTE, m1+30);
cal1.set(Calendar.SECOND, 00);
Intent intent = new Intent(context, YourBroadCastReceiver.class);
// Add Some unique ID here for e.g "SFSF43535"
PendingIntent openAlarm = PendingIntent.getBroadcast(context, 0, intent, 0);
// Add Some unique ID here for e.g "SFSf87sfs"
PendingIntent CloseAlarm = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
cal1.getTimeInMillis(), DateUtils.DAY_IN_MILLIS, openAlarm);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
cal1.getTimeInMillis(), DateUtils.DAY_IN_MILLIS, CloseAlarm);
YourBroadCastReceiver (这里我需要唯一的ID)
@Override
public void onReceive(Context context, Intent intent) {
// Get Unique id here to find some data related to that alram
}
答案 0 :(得分:1)
您可以在Intent
中添加附加内容,这些附加内容将被传递:
Intent intent = new Intent(context, YourBroadCastReceiver.class);
intent.putExtra("id", "somerandomID");
然后将多余的东西退回接收器:
public void onReceive(Context context, Intent intent) {
String id = intent.getStringExtra("id");
答案 1 :(得分:0)
Intent intentOpen = new Intent(context, YourBroadCastReceiver.class);
intentOpen.putExtra("id", 1);
PendingIntent openAlarm = PendingIntent.getBroadcast(context, 0, intentOpen, 0);
Intent intentClose = new Intent(context, YourBroadCastReceiver.class);
intentClose.putExtra("id", 2);
PendingIntent CloseAlarm = PendingIntent.getBroadcast(context, 0, intentClose, 0);
并在收到后
public void onReceive(Context context, Intent intent) {
int AlarmId = intent.getExtras().getInt("id");
if(AlarmId==1)
{
}else if(AlarmId==2)
{
//Cancle
Intent myIntent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,
AlarmId, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
pendingIntent.cancel();
manager.cancel(pendingIntent);
}
}