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 秒后消失的通知?

4

2 回答 2

5

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

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

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

如果您想使用 Timer 而不是Handler. 然后你可以尝试:

Timer timer = new Timer();
  timer.schedule(new TimerTask()
{
   public void run()
   {
     notificationManager.cancel(YourNotificationId);
   }},delayInMilliseconds);
}
于 2013-07-15T14:07:39.197 回答
1

您可以使用方法cancel(int id)cancelAll()关闭通知。启动一个定时器 5 秒,当它结束时调用 cancel(); http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)

于 2013-07-15T14:02:31.457 回答