我遇到的问题是,如果我将 c2 设置为日历时间,比如从现在起 24 小时,应该显示通知,尽管如果我在手机上执行重新启动,那么通知将不再显示在给定时间。
我在课堂上使用以下代码根据我使用 c2 设置的特定日历时间来安排事件。
Intent myIntent = new Intent(Appointments.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(Appointments.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, c2.getTimeInMillis(), pendingIntent);
我曾经根据 c2 设置的挂起意图激活的服务类也将在 MyAlaramService 中执行以下操作.class
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
NotificationManager mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),Appointments.class);
Notification notification = new Notification(R.drawable.icon,"Appointment Reminder For Tommorow!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), "myCF Reminder", "Appointment Tommorw!", pendingNotificationIntent);
mManager.notify(0, notification);
this.stopSelf();
}
如果我在手机上执行重启,则通知将不再在给定时间显示
您需要在重新启动后获得控制权,例如通过 BOOT_COMPLETED
BroadcastReceiver
,并重新建立AlarmManager
事件计划。
此示例项目演示了基础知识,尽管这是一个非常简单的示例。
另外,请注意,将RTC_WAKEUP
与服务PendingIntent
一起使用是不可靠的。如果您想使用_WAKEUP
警报,请使用 WakefulBroadcastReceiver
或 我的WakefulIntentService
。这是我上面链接到的同一示例的版本,它们使用 WakefulIntentService
和 WakefulBroadcastReceiver
.