在Android 11及以下版本中,可以通过将通知的优先级设置为“高”来启用Heads-up通知,但在Android 12中,需要在通知的创建过程中设置特定的参数才能启用此功能。以下是一个示例:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setFullScreenIntent(fullScreenIntent, true)
.setNotificationSilent()
.setAllowSystemGeneratedContextualActions(true);
// Enable heads-up notifications for Android 12
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
builder.setHapticShim(1);
builder.setFlag(Notification.FLAG_GESTURE_DISMISSIBLE);
builder.setPriority(NotificationCompat.PRIORITY_MAX);
}
Notification notification = builder.build();
在上面的示例中,我们在构建通知时检查Android版本,如果设备运行的是Android 12或更高版本,我们就使用setHapticShim(1)
启用触觉反馈,使用setFlag(Notification.FLAG_GESTURE_DISMISSIBLE)
启用手势取消通知,并将优先级设置为NotificationCompat.PRIORITY_MAX
来启用Heads-up通知。