【问题标题】:Notification Auto Cancel at a Particular Time在特定时间自动取消通知
【发布时间】:2015-12-24 07:20:06
【问题描述】:

我是 Java 编码的初学者,目前正在编写一个 Android 项目。现在,我面临一个问题。我希望我的application 在特定时间自动删除notification

在用户点击notification 后,我设法关闭了notification。但是,与此同时,如果用户没有对notification 做出反应,我还希望notification 在特定时间后自动消失。

请告诉我应该怎么做。如果可能的话,请给我一些例子。

【问题讨论】:

    标签: java android notifications broadcastreceiver alarmmanager


    【解决方案1】:

    您可以在调用显示通知的方法后立即启动一个计时器,并在计时器的 onFinish() 内添加如下内容:

    NotificationManager nMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nMgr.cancelAll();
    

    【讨论】:

      【解决方案2】:

      您可以设置一个计时器或类似闹钟之类的东西,当满足您的条件时,使用以下命令取消它:

       //clear all pending notifications
              String ns = Context.NOTIFICATION_SERVICE;
              NotificationManager nMgr = (NotificationManager) context.getSystemService(ns);
              nMgr.cancelAll();
      

      【讨论】:

        【解决方案3】:

        您可以使用Timer 获取所需的时间,删除Notification 您可以使用cancel()

        nMgr.cancel(<notification-id>); // here you have to pass your notification id.
        

        如果您想删除所有通知,只需使用

        nMgr.cancelAll();
        

        如果您想在 2 秒后删除通知,您可以使用:

            Timer timer=new Timer();
            TimerTask task=new TimerTask() {
        
                @Override
                public void run() {
                    nMgr.cancel(notification-id);
                }
            };
        
            timer.schedule(task, 2000);
        

        【讨论】:

          【解决方案4】:

          我建议使用处理程序方法从通知栏中删除通知。您可以在处理程序处指定时间长度(以毫秒为单位)。这只会在输入的时间后调用一次。

           Handler h = new Handler();
          long delayInMilliseconds = 5000;
          h.postDelayed(new Runnable() {
              public void run() {
                  mNotificationManager.cancel(YourNotificationId);
              }
          }, delayInMilliseconds);
          

          【讨论】:

            猜你喜欢
            • 2012-11-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-09-15
            • 2015-02-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多