Android Heads-up notification disappears after a few seconds

后端 未结 5 524

I would that the notification does not disappear after a few seconds. So i have create the notification like this:

  NotificationCompat.Builder builder = new         


        
5条回答
  •  长情又很酷
    2020-12-07 04:32

    You can do it with:

    notificationBuilder.setFullScreenIntent(pendingIntent, true)
    

    You also have to use these:

    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)
    

    IMPORTANT:

    On most of the devices, this will show the notification on the top of the screen, overlapping everything, and staying there.

    BUT ON SOME DEVICE THIS WILL IMMEDIATELY LAUNCH THE PENDING INTENT THAT IS GIVEN TO THE NOTIFICATION. (Eg. Huawei)

    TO SOLVE THIS we can use a dummy pendingIntent for the fullScreenIntent, that shows the notification the same way, just without the notificationBuilder.setFullScreenIntent(pendingIntent, true); This will work as a fallback, so the notification will appear, but will shrink itself to the status bar after like 5 seconds.

    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)
    

    Where:

    class FullScreenIntentService : Service() {
    
        override fun onCreate() {
            super.onCreate()
            showNotificationHereTheSameWayJustWithoutSetFullScreenIntent()
            stopSelf()
        }
    
        override fun onBind(intent: Intent?): IBinder? = null
    }
    

    And don't forget to register the service in AndroidManifest.

提交回复
热议问题