在通知栏中显示几秒钟的通知?

3
我该如何在通知栏中创建一个5秒后消失的通知?例如,这是通知代码:
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// Build notification
// Actions are just fake
Notification noti = new Notification.Builder(this)
        .setContentTitle("Notification")
        .setContentText("This is a notification that didsappears in 5 seconds")
        .setSmallIcon(R.drawable.icon)
        .setContentIntent(pIntent)
        .addAction(R.drawable.icon)


NotificationManager notificationManager = 
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


notificationManager.notify(0, noti);

从这段代码开始,我该如何创建一个在5秒钟后消失的通知?

2
在五秒钟后简单地取消通知。 - Steelight
是的,这就是我想做的,但我不知道在哪里放置代码以及使用哪些代码。 - David_D
2个回答

5

您可以在5秒后简单地取消通知。为此,您可以使用 Timer Handler 。这里是 Handler 的解决方案:

 Handler handler = new Handler();
 long delayInMilliseconds = 5000;
 handler.postDelayed(new Runnable() {

    public void run() {
        notificationManager.cancel(YourNotificationId);
    }}, delayInMilliseconds);

if you want to use Timer instead of Handler. Then you can try:

Timer timer = new Timer();
  timer.schedule(new TimerTask()
{
   public void run()
   {
     notificationManager.cancel(YourNotificationId);
   }},delayInMilliseconds);
}


@David_D 在创建通知后5秒钟将调用此方法。所以当然是的。或者您在“正在运行的通知”方面有其他意思吗? - user1744056
我指的是一个永久的通知.. 因此,当通知开始后,只有在5秒钟之后才会被删除,而不是通过滑动它来取消。你明白吗? - David_D

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接