How to remove the notification after the particular time in android?

后端 未结 5 1958
余生分开走
余生分开走 2021-01-05 00:19

I am creating an simple android application in that created a notification.

Now i want to remove the notification if the user doesn\'t response after the particular

5条回答
  •  生来不讨喜
    2021-01-05 00:43

    For Android >= 8.0 (Oreo) we can use this,

    NotificationCompat.Builder#setTimeoutAfter(long)

    For Android < 8.0 we can use AlarmManager

    Add this to AndroidManifest.xml :

    
    

    Create AutoDismissNotification.kt and add this code :

    class AutoDismissNotification : BroadcastReceiver() {
    
        companion object {
            private const val KEY_EXTRA_NOTIFICATION_ID = "notification_id"
        }
    
        override fun onReceive(context: Context, intent: Intent) {
            val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.cancel(intent.getIntExtra(KEY_EXTRA_NOTIFICATION_ID, 0))
        }
    
        fun setAlarm(context: Context, notificationId: Int, time: Long) {
            val alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val alarmIntent = Intent(context, AutoDismissNotification::class.java)
            alarmIntent.putExtra(KEY_EXTRA_NOTIFICATION_ID, notificationId)
            val alarmPendingIntent = PendingIntent.getBroadcast(context, notificationId, alarmIntent, PendingIntent.FLAG_ONE_SHOT)
            alarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, alarmPendingIntent)
        }
    
        fun cancelAlarm(context: Context, notificationId: Int) {
            val alarmIntent = Intent(context, AutoDismissNotification::class.java)
            alarmIntent.putExtra(KEY_EXTRA_NOTIFICATION_ID, notificationId)
            val alarmPendingIntent = PendingIntent.getBroadcast(context, notificationId, alarmIntent, PendingIntent.FLAG_ONE_SHOT)
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            alarmManager.cancel(alarmPendingIntent)
        }
    }
    

    When you build the notification, add this :

    long timeOut = 5 * 1000L; // Five seconds
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        builder.setTimeoutAfter(timeOut);
    }
    else {
        AutoDismissNotification().setAlarm(this, notificationId, timeOut);
    }
    

提交回复
热议问题