Clear a Status Notification Android

大兔子大兔子 提交于 2019-12-11 23:09:33

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/8841078/clear-a-status-notification-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!