我正在尝试在特定时间设置通知,但通知未显示确切时间。
有时通知会在正确的时间发出,有时会延迟10-15秒。
private void showNotification(long lastScratched) {
Intent intent = new Intent(getActivity(), NotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
lastScratched = lastScratched + timeInterval;
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, lastScratched, pendingIntent);
Log.e("MyNotification", "Next Notification Time : "+lastScratched+"");
}
NotificationReceiver.java
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "my_channel_01")
.setContentIntent(pendingIntent)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.app_icon))
.setSmallIcon(R.drawable.app_icon)
.setContentTitle("Notification Title")
.setContentText("Notification Text")
//.setPriority(Notification.PRIORITY_MAX)
.setSound(alarmSound)
.setAutoCancel(true);
notificationManager.notify(100, builder.build());
}
}
答案 0 :(得分:2)
使用setExactAndAllowWhileIdle或JobSchreduler。
对于setExactAndAllowWhileIdle,您可以使用:
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);