我想在每天早上6点30分的特定时间显示我的应用程序的通知。我成功地做到了。以下是在指定时间执行的代码。但是,只有当应用程序处于打开状态或放到后台时,代码才有效。如果我重新启动设备并且不启动应用程序,它就不起作用,如果我杀了应用程序也无效。
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent;
alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, MyReceiver.class);
alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,6);
calendar.set(Calendar.MINUTE,30);
calendar.set(Calendar.AM_PM,Calendar.AM);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
alarmIntent);
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
以下是接收方BroadCast方法
@Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);
}
警报服务类显示通知。
/ ...显示通知... /