我试图创建一个警报,触发按钮点击,并将在早上6:00重复。我做的第一个工作正常,但是当我添加另一个重复警报时,它同时触发了上一个警报。所以我的问题是如何才能使多重警报正常工作?
重复闹钟的代码
public void setAlarmRepeating()
{
AlarmManager dog=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent alarm_dog=new Intent(this,Dog_alarm.class);
PendingIntent pi1 = PendingIntent.getBroadcast(this, 100,alarm_dog, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND, 00);
dog.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi1);
AlarmManager dog1=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent alarm_dog1=new Intent(this,Dog_alarm.class);
PendingIntent pi2 = PendingIntent.getBroadcast(this, 200,alarm_dog1, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar1 = Calendar.getInstance();
calendar1.set(Calendar.HOUR_OF_DAY, 7);
calendar1.set(Calendar.MINUTE,0);
calendar1.set(Calendar.SECOND, 00);
dog1.setRepeating(AlarmManager.RTC_WAKEUP,calendar1.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi2);
}
这适用于BroadcastReciever
public class MorningAlarm extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager1=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
Intent dog_intent1=new Intent(context,HomeActivity.class);
dog_intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent dog_pending1=PendingIntent.getActivity(context, 100,dog_intent1, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder1=new NotificationCompat.Builder(context)
.setContentIntent(dog_pending1)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("Pet Guide 101")
.setContentText("Time to feed your dog")
.setAutoCancel(true);
notificationManager1.notify(100,builder1.build());
NotificationManager notificationManager2=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
Intent dog_intent2=new Intent(context,HomeActivity.class);
dog_intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent dog_pending2=PendingIntent.getActivity(context, 200,dog_intent2, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder2=new NotificationCompat.Builder(context)
.setContentIntent(dog_pending2)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("Pet Guide 101")
.setContentText("Time to walk your dog")
.setAutoCancel(true);
notificationManager2.notify(200,builder2.build());
}
}
答案 0 :(得分:0)
当您使用PendingIntent.FLAG_UPDATE_CURRENT
标记当前PendingIntent
更新新的附加内容并且未创建新的PendingIntent
时。
您必须为每个闹钟创建新的PendingIntent
。
使用:
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
请记住取消闹钟,您必须重启设备或卸载应用
答案 1 :(得分:0)
我认为这是因为您的警报管理员没有将您的任务视为时间紧迫的
您需要使用setInexactRepeating()
而不是setRepeating()
函数。
希望它能工作。