我希望我的用户设置一个时间从我的应用程序接收每日提醒。在我的ReminderActivity中,我创建了PendingIntent和Alarm Manager,然后在我的Alarm Receiver类中,我在onReceive()中创建了通知。我在创建挂起的意图时尝试了FLAG_CANCEL_CURRENT和FLAG_UPDATE_CURRENT标志,但是当我测试应用程序并更改提醒时间时,有时候通知根本没有到达,或者只有当应用程序在后台运行时才会到达屏幕亮起。我非常感谢任何想法或想法。
ReminderActivity代码:
private void setNotification() {
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, chosenHour);
calendar.set(Calendar.MINUTE, chosenMinute);
calendar.set(Calendar.SECOND, 0);
//if user sets the alarm after their preferred time has already passed that day
if(now.after(calendar)) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(ReminderActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
警报接收器代码:
@Override
public void onReceive(Context context, Intent intent) {
Bitmap largeLogo = BitmapFactory.decodeResource(context.getResources(),
R.drawable.ptwired_logo);
//create local notification
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
//notificationIntent.putExtra("FromPTWired", true); //to track if user opens the app from the daily digest notification
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ptwired_logo)
.setLargeIcon(largeLogo)
.setContentTitle(context.getResources().getString(R.string.app_name))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setContentText(REMINDER_TEXT)
.setAutoCancel(true)
.setOngoing(false)
.build();
notificationManager.notify(1, notification);
}
}
答案 0 :(得分:0)
可能是打盹模式的问题,请看一下Android限制:
打盹限制
以下限制适用于您在Doze中的应用:
标准AlarmManager警报(包括setExact()和setWindow())将延迟到下一个维护窗口。
如果需要设置在Doze中触发的警报,请使用setAndAllowWhileIdle()或setExactAndAllowWhileIdle()。
使用setAlarmClock()设置的警报继续正常启动 - 系统在警报触发前不久退出Doze。