Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove ongoing notification from service

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);
like image 832
NikolajSvendsen Avatar asked Oct 20 '25 14:10

NikolajSvendsen


1 Answers

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

like image 94
nicholas.hauschild Avatar answered Oct 22 '25 03:10

nicholas.hauschild



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!