警报管理器和广播接收器未在正确的时间显示通知 - Android

Alarm Manager & Broadcast Receiver not showing notification at correct time - Android

我试图在特定时间设置通知,但通知没有在准确时间显示。

有时通知会在正确的时间到达,有时会有 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());
    }
}

使用setExactAndAllowWhileIdle or JobSchreduler.

对于 setExactAndAllowWhileIdle,您可以使用:

AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);