首先,要确保你使用的通知渠道允许悬浮通知。如果通知渠道不允许悬浮通知,即使代码中设置了悬浮通知,它也不会生效。可以通过以下代码示例进行设置:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Channel name",
NotificationManager.IMPORTANCE_HIGH);
channel.enableVibration(true);
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
channel.setImportance(NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("Channel description");
channel.setBypassDnd(true);
channel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + context.getPackageName() + "/" + R.raw.notification_sound), null);
channel.setShowBadge(true);
channel.enableLights(true);
channel.setLightColor(Color.RED);
NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
通过这个代码示例,可以设置通知渠道为允许悬浮通知。
如果应用程序在前台运行,可以使用以下代码示例将通知设置为悬浮通知:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
notificationBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE);
notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
} else {
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
}
如果应用程序在后台运行,可以使用以下代码示例将通知设置为悬浮通知:
if (Build.VERSION
上一篇:Android通知不弹出