android - 在通知栏中通知几秒钟?

标签 android notifications statusbar android-notifications

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

最佳答案

您可以在 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);
}

关于android - 在通知栏中通知几秒钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655879/

相关文章:

react-native - 状态栏不尊重 'barStyle' 属性

iphone - 将 UIView 或 UIWindow 放置在 Statusbar 上方

uinavigationcontroller - iOS8中UIImagePickerController隐藏状态栏问题

java - 在android源码中找不到自己创建的文件路径

Android 错误构建签名的 APK : keystore. jks 未找到用于签名配置 'externalOverride'

Android 前台服务通知替换

java - 按下音量按钮时如何使通知静音?

android - 用户通过滑动删除华为设备后在前台重新启动通知(如 Strava/Endomondo)

android - 增加代码缓存容量没有止境

java - Android应用程序: scanning for music files in specified folders runs slowly and hangs.