Search code examples
androidandroid-notification-bar

Clear a Status Notification Android


Im having difficulty clearing a status bar Notification.

public void NotificationStatus(){

    Intent intent = new Intent(this, Stimulation.class);   
    NotificationManager notificationManager
        = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Notification notification = new Notification(
        david.flanagan.android.VenAssist.Activities.R.drawable.notification_icon,
        "VenAssist Stimulation ON", System.currentTimeMillis());
    PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notification.flags |= Notification.DEFAULT_VIBRATE;
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.setLatestEventInfo(this, "VenAssist",
        "Stimulation Started", activity);
    notificationManager.notify(0, notification);     
}

I'm then trying to clear the notification status in the onDestroy() function of my service by calling

notification.cancel(0);

I have created an instance of the notification, which im not sure is correct.

private NotificationManager notification;

When I try to cancel the service, hence clear the status bar, the app crashes.


Solution

  • Your notification object may be null, which would cause a NullPointerException.

    I think you should be using a NotificationManager object to cancel a notification, use the same id (in your case, 0) and pass that to NoticationManager.cancel(Int):

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.cancel(0);
    

    NotificationManager docs