安卓工作室中的通知未按时送达



我目前正在使用java在android studio上开发一个应用程序,我希望用户能够从他们创建的日历事件中接收通知。然而,我的通知没有按时到达,因为它们要么滞后,要么就是没有显示。

这是我为设置通知的报警接收器编码:

public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String event = intent.getStringExtra("event");
String time = intent.getStringExtra("time");
int notId = intent.getIntExtra("id", 0);
Intent activityIntent = new Intent(context, CalendarActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, activityIntent, PendingIntent.FLAG_ONE_SHOT);
String channelId = "channel_id";
CharSequence name = "channel_name";
String description = "description";
NotificationChannel channel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH);
channel.setDescription(description);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentTitle(event)
.setContentText(time)
.setDeleteIntent(pendingIntent)
.setGroup("Group_calendar_view")
.build();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(notId,notification);
}
}

这是我设置警报的CustomCalendarView活动:

private void setAlarm(Calendar calendar, String event, String time, int RequestCode){
Intent intent = new Intent(context.getApplicationContext(), AlarmReceiver.class);
intent.putExtra("event",event);
intent.putExtra("time",time);
intent.putExtra("id",RequestCode);
@SuppressLint("UnspecifiedImmutableFlag") PendingIntent pendingIntent = PendingIntent.getBroadcast(context,RequestCode,intent,PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)context.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() ,pendingIntent);
}

例如:当我将闹钟设置为上午10:20时,通知要么不会弹出,要么像上午10:22那样弹出得很晚。请帮忙!如果我需要提供更多信息,请告诉我。

您应该使用准确的警报器来按时发出警报,

使用alarmManager.setExact((而不是alarmManager.set((.

setExact((方法类似于set((,但不允许操作系统调整交付时间。警报将尽可能接近请求的触发时间。

设置setExact((而不是设置

alarmManager.setExact(…(;

但随着设备和接口更新的不同,应用程序工作的性能因设备而异,在这种情况下,您必须放置一些settings in your application such as Disable Software Battery Optimizations, make the application run in the background even after closing, give Permissions Autostart, turn on all notifications and display them etc.。最后,调用ActivityonStop((事件中的函数。

是,正确。你应该要求用户允许电池优化,在安卓12或更高版本中,你应该让用户启用报警&提醒权限。

但是,当你的应用程序想要准确地按时发出警报时,你必须使用准确的警报。

最新更新