Remove ongoing notification from service

2019-07-08 08:48发布

问题:

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...