我正在尝试运行两个警报来显示通知,一个是每天一个,每小时一个,在同一个接收器类中并使用相同的功能,但问题是,当我分配一个时,另一个也在我重新启动设备后被分配因为BOOT_COMPLETED,所以我想知道有什么办法可以实现这个目标吗?
我的alarm_receiver类: -
public class alarmreceiver extends BroadcastReceiver {
static int id;
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm running", Toast.LENGTH_SHORT).show();
start(context,id);
}
static void start(Context context,int id) {
if (id==1) {
Intent intent = new Intent(context, notification_receiver.class);
PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 60 * 1000
, pendingintent);
} else
if (id == 2) {
Intent intent = new Intent(context, notification_receiver.class);
PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 10);
calendar.set(Calendar.MINUTE, 14);
calendar.set(Calendar.AM_PM, Calendar.PM);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingintent);
}
}
}
我在按钮点击事件下的主要活动中调用此功能: -
butn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (r1.isChecked()) {
alarmreceiver.start(getApplicationContext(),2);
Toast.makeText(getApplicationContext(), "Daily Affirmations Scheduled", Toast.LENGTH_SHORT).show();
//
}
if(r2.isChecked())
{
alarmreceiver.start(getApplicationContext(),1);
Toast.makeText(getApplicationContext(), "Hourly Affirmations Scheduled", Toast.LENGTH_SHORT).show();
}
如何通过使用相同的警报接收器类和使用功能来实现这一目标?感谢。
答案 0 :(得分:0)
您需要使PendingIntent
唯一。目前,您对PendingIntent.getBroadcast()
的两次通话都返回相同的PendingIntent
。
改变这个:
PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
到此:
PendingIntent pendingintent = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
提供id
参数会使PendingIntent
唯一。