在显示之前取消安装的Android安排通知

时间:2017-03-07 12:38:41

标签: android notifications android-notifications

如果尝试在第一个通知的15秒内发送另一个通知,我试图取消我已请求发送给用户的通知。

这是我的代码:

全局变量:

    public NotificationManager nm;

通知功能:

    final NotificationCompat.Builder b = new NotificationCompat.Builder(this);

    b.setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                    R.mipmap.ic_launcher))
            .setContentTitle(title)
            .setContentText(message);

    if (nm != null) {
        Log.d(TAG, "notifyThis: cancelled");
        nm.cancelAll();
    } else {
        Log.d(TAG, "notifyThis: not cancelled");
    }

    nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            nm.notify(1, b.build());
            Log.d(TAG, "notifyThis: notify");

        }
    }, 15000);

我注意到在发布通知之前,nm仍然为空,因此此方法无法正常工作,但我需要一种方法在创建通知后,在通过.notify发布通知之前删除通知

感谢。

1 个答案:

答案 0 :(得分:1)

理想情况下,您不希望依赖于变量的null状态 相反,Handler类具有删除以前计划的任务的方法。为此,您需要保留对Handler和Runnable对象的引用。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div class="container">
    <div class="cmd">
      <p class="init">$Robot~ </p>
      <p class="perc"> </p>
    </div>
  </div>
</body>
相关问题