Remove ongoing notification from service

守給你的承諾、 提交于 2019-12-11 01:53:31

问题


I have a service that create a notification when it is started.

And then ondestroy() i want it to be removed.

I just use .cancel(NOTIFICATION_ID);

It works great when it is a normal notification but when i am using ongoing event it just won't cancel it.

I did read something about that services doesn't stop if android have the resources for it, but how to overcome this?

I use this code to start the service

    final Intent bg_service = new Intent(BackgroundService.class.getName());

    btn_start = (Button)findViewById(R.id.btn_start);
    btn_stop = (Button)findViewById(R.id.btn_stop);

    btn_start.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            startService(bg_service);
        }
    });

    btn_stop.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            stopService(bg_service);
        }
    });

I use this in on create

            notificationManager = (NotificationManager) 
            getSystemService(NOTIFICATION_SERVICE);

    Notification notification = new Notification(R.drawable.ic_launcher,
            "A new notification", System.currentTimeMillis());

    notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;

    Intent intent = new Intent(this, mainapp.class);
    PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
    notification.setLatestEventInfo(this, "...",
            "...", activity);
    notificationManager.notify(19314, notification);

And this in on destroy

            noficationManager.cancel(19314);

回答1:


I would look at doing 'ongoing' notifications a bit differently if you can. There are methods that live on Service that are dedicated to adding and removing an 'ongoing' notification.

Service.startForeground(int, Notification)

Service.stopForeground(boolean)

Perhaps you could just try calling stopForegroud(boolean) from your onDestroy() method first...



来源:https://stackoverflow.com/questions/9302002/remove-ongoing-notification-from-service

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