I am trying to cancel a notification I have requested to be sent to the user if another notification is trying to be sent within 15 seconds of the first one.
This is my code:
Global variable:
public NotificationManager nm;
Notify function:
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);
I've noticed that nm remains null until the notification is posted so this method doesn't work, but I need a way to remove a notification after creating the notification, and before it is posted by .notify.
Thanks.