先来说一下AlarmManager的使用方法
Intent intent1 = new Intent("ELITOR_CLOCK_STARTUP");
intent1.putExtra("msg", "开机时间到了");
PendingIntent pi = PendingIntent.getService(context, 0, intent1, PendingIntent.FLAG_ONE_SHOT);
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, 14);
c.set(Calendar.MINUTE, 20);
c.set(Calendar.SECOND, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
am.setExactAndAllowWhileIdle(AlarmManager.RTC_POWEROFF_WAKEUP, c.getTimeInMillis(), pi);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setExact(AlarmManager.RTC_POWEROFF_WAKEUP, c.getTimeInMillis(), pi);
} else {
am.set(AlarmManager.RTC_POWEROFF_WAKEUP, c.getTimeInMillis(), pi);
}
这是我一贯的写法,但如果设置多个提醒事件时,总是最后一个有效,在网上找了好久终于得到了解决,用这篇博客来提醒一下自己
问题出在这一行
pi = PendingIntent.getService(context, 0, intent1, PendingIntent.FLAG_ONE_SHOT);
解决办法
PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, int flags);
第二个参数requestCode一定要是唯一的,比如不同的ID之类的,(如果系统需要多个定时器的话)。