你可以这样做:
notificationBuilder.setFullScreenIntent(pendingIntent, true)
您还必须使用这些:
val tempChannel = NotificationChannel(tempChannelId, "temp channel",
NotificationManager.IMPORTANCE_HIGH) // Setting to high is important
tempChannel.enableVibration(true)
...
notificationBuilder.setAutoCancel(false)
notificationBuilder.setPriority(NotificationCompat.PRIORITY_MAX) // PRIORITY_HIGH works too
notificationBuilder.setVibrate(LongArray(0)) // For older devices we need to add vibration or sound for the Heads-Up notification. This line will not make it vibrate, you can use another pattern, or default, if you want it to vibrate
notificationBuilder.setFullScreenIntent(pendingIntent, true)
重要的:
在大多数设备上,这将在屏幕顶部显示通知,重叠所有内容并停留在那里。
但在某些设备上,这将立即启动通知中的未决意图。(例如华为)
为了解决这个问题,我们可以为 fullScreenIntent 使用一个虚拟的 pendingIntent,它以相同的方式显示通知,只是没有notificationBuilder.setFullScreenIntent(pendingIntent, true);
这将作为后备,所以通知会出现,但会在 5 秒后自行缩小到状态栏。
val servicePendingIntent = PendingIntent.getService(context, 0, Intent(context, FullScreenIntentService::class.java), 0)
val mainActivityPendingIntent = PendingIntent.getActivity(context, 0, Intent(context, MainActivity::class.java), PendingIntent.FLAG_ONE_SHOT)
...
notificationBuilder.setContentIntent(mainActivityPendingIntent)
notificationBuilder.setFullScreenIntent(servicePendingIntent, true)
在哪里:
class FullScreenIntentService : Service() {
override fun onCreate() {
super.onCreate()
showNotificationHereTheSameWayJustWithoutSetFullScreenIntent()
stopSelf()
}
override fun onBind(intent: Intent?): IBinder? = null
}
并且不要忘记在 AndroidManifest 中注册服务。