其他详细信息 h2>
在您的代码中,您似乎正在安排警报,而不是在将来的某个时间。我建议以下内容来创建警报:
Calendar c = Calendar.getInstance();
// don't do this:
// c.setTimeInMillis(System.currentTimeMillis()); // This just sets the alarm time to "now"
// set the calendar to 8:00 pm:
c.set(Calendar.HOUR_OF_DAY, 20);
c.set(Calendar.MINUTE, 0);
long alarmTime = c.getTimeInMillis();
Intent it = new Intent(ServiceClass.getClass());
// Even though the docs say that the request code doesn't matter making it unique tells the alarmManager that it's a different PendingIntent
PendingIntent pendingIntent = PendingIntent.getService(this, 0, it, 0);
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); // set the first alarm for 8:00
c.set(Calendar.MINUTE, 30);
Intent it2 = new Intnt(ServiceClass.getClass());
PendingIntent pi2 = PendingIntent.getService(this, 0, it2, 0);
alarmMgr.set(AlarmManager.RTC_WAKEUP, alarmTime, pi2); // set the second alarm for 8:30这条线
Intent it = new Intent(ServiceClass.getClass());将启动Class ServiceClass:
class ServiceClass extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO TRAVIS Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) { // onStartCommand is run when the service is started by the AlarmManager
// build and set the notification here
NotificationManager notifMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// build notification
Notification notification = new Notification.Builder(getApplicationContext())
.setContentTitle("New mail from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build();
int ID = 0;
notifMgr.notify(ID++, notification); // use a unique id every time if you want multiple notifications (sounds like what you want, but not a best practice)
notification = new Notification.Builder(getApplicationContext())
.setContentTitle("New event from " + sender.toString())
.setContentText(subject)
.setSmallIcon(R.drawable.new_mail)
.setLargeIcon(aBitmap)
.build();
notifMgr.notify(ID++, notification); // add the second notification to the notification bar
return super.onStartCommand(intent, flags, startId);
}
}您的问题的答案:
1 - 通过在将来的某个时间设置闹钟,你要求操作系统在指定的时间启动你的PendingIntent(在你的情况下,发送一个广播;在我的上面,一个服务)(这就是你需要设置的原因)日历到将来某个时间的时间!)
2 - 创建多个警报是在适当的时间调用具有不同PendingIntent的警报管理器(当您希望它们触发时)。对于Notification来说也是如此,创建多个(具有唯一ID)。