【问题标题】:Notification for several seconds in notifications bar?通知栏中的通知几秒钟?
【发布时间】:2013-07-13 09:56:31
【问题描述】:

如何在通知栏中创建一个 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 秒后消失的通知?

【问题讨论】:

  • 只需在五秒后取消通知。
  • 是的,这就是我想做的,但我不知道代码放在哪里以及代码使用什么..

标签: android notifications statusbar android-notifications


【解决方案1】:

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

 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);
}

【讨论】:

  • 谢谢,稍后我会试试:)
  • @David_D 这个方法会在你创建通知后 5 秒被调用。所以当然是的。或者你的意思是“持续通知”?
  • 我的意思是永久通知。因此,通知开始时将仅在 5 秒后延迟,而不是在其上滑动。你明白吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多