我想发送定时通知(每天早上 5:00),并尝试使用 AlarmManager 和以下代码来做到这一点:
Intent appIntent = new Intent(this, NotificationService.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent penIntent = PendingIntent.getService(this, 0,
appIntent, 0);
alarmManager.cancel(penIntent);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 5);
cal.set(Calendar.MINUTE, 00);
cal.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, penIntent);
NotificationService.class 看起来(至少是重要部分)如下所示:
int id = 001;
NotificationManager mNotifyMng = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
MainActivity.this).setSmallIcon(R.drawable.icon).setContentTitle("Test")
.setContentText("Test!");
mNotifyMng.notify(id, mBuilder.build());
stopSelf();
我似乎无法让它工作。当我将模拟器时钟设置为 4:59 或其他时间并等待它更改为 5:00 时,没有出现任何通知,我想不出另一种方法来测试它。我希望你知道一些方法来测试它或在我的代码中找到错误。