此问题可能是由于通知渠道未正确设置导致的。在创建通知之前,请使用以下代码创建通知渠道:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// 设置通知渠道的ID、名称和描述
String channelId = "my_channel_id";
CharSequence channelName = "My Channel";
String channelDescription = "Channel Description";
int importance = NotificationManager.IMPORTANCE_HIGH;
// 创建通知渠道
NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
channel.setDescription(channelDescription);
// 注册通知渠道
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
然后,在发送通知时,请确保已使用正确的通知渠道 ID:
String channelId = "my_channel_id";
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(0, builder.build());