问题描述: 在API Level 28上,AlarmReceiver的通知不显示。
解决方法:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 创建通知渠道
NotificationChannel channel = new NotificationChannel("channel_id", "channel_name",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("channel_description");
// 在系统通知管理器中注册通知渠道
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "channel_id")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Notification Title")
.setContentText("Notification Content")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
Intent intent = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// 在API Level 23及以上,使用setExactAndAllowWhileIdle()方法
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 在API Level 19及以上,使用setExact()方法
alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
}
以上是一些可能导致AlarmReceiver通知不显示的常见问题和解决方法,根据具体情况逐步排查可能存在的问题并进行修复。