我正在创建一款简单的安卓应用程序,并在其中创建了一个通知。
现在,如果用户在特定时间内没有响应,我想要移除该通知。
也就是说,我想在五分钟后移除通知。
我正在创建一款简单的安卓应用程序,并在其中创建了一个通知。
现在,如果用户在特定时间内没有响应,我想要移除该通知。
也就是说,我想在五分钟后移除通知。
目前正确的解决方案可能是使用:
AlarmManager更常用于需要在应用关闭时在后台运行的复杂服务。对于简单的小线程,您也可以在Handler中使用经典的Java Runnable。
Handler h = new Handler();
long delayInMilliseconds = 5000;
h.postDelayed(new Runnable() {
public void run() {
mNotificationManager.cancel(id);
}
}, delayInMilliseconds);
还可以在这里查看:
您也可以使用TimerTask类。
对于 Android < 8.0,我们可以使用 AlarmManager。
<receiver
android:name=".AutoDismissNotification"/>
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)
}
}
long timeOut = 5 * 1000L; // Five seconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setTimeoutAfter(timeOut);
}
else {
AutoDismissNotification().setAlarm(this, notificationId, timeOut);
}
NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
.setSmallIcon(Util.getNotificationIcon(context))
.setContentTitle(new SessionManager().getDomainPreference(context))
.setAutoCancel(true)
.setOngoing(false)
.setPriority(NotificationCompat.PRIORITY_MAX)
.setShowWhen(false)
.setContentText(summaryText)
.setTimeoutAfter(3000) // add time in milliseconds
.setChannelId(CHANNEL_ID);