Remove notification when service destroyed by android OS
Asked Answered
B

5

10

I created an app which shows Notification when Service.onStartCommand() method executed and hide notification when Service.onDestroy() is called. Its works fine for normal calls to startService() and stopService().

Service Code:

@Override
public IBinder onBind(Intent intent) 
{
    return null;
}
@Override
public void onCreate() 
{
    super.onCreate();
    nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    //Some  code here
    showNotification();
    return START_NOT_STICKY; 
}

@Override
public void onDestroy() 
{
    super.onDestroy();
    nm.cancel(R.string.service_started);
}

Problem: When my service is destroyed by android OS() (In case when onDestroy() not called) then notification not removed. So how to remove notification when Service is destroyed by android OS itself?

Behrens answered 13/9, 2012 at 6:33 Comment(0)
G
1

Always call your code BEFORE super.onDestroy(); and not AFTER

@Override
public void onDestroy() 
{
    nm.cancel(R.string.service_started);
    super.onDestroy();
}
Grandparent answered 7/2, 2019 at 12:39 Comment(1)
this also does not always work. onDestroy might be skipped by androidBradney
M
0

You should use this where ever u want to stop the service,that will close your notification and end service.

stopService(new Intent(MainActivity.this,MyService.class));
Margarettemargarida answered 24/7, 2014 at 5:36 Comment(0)
W
0

Have you tried notificationManager.cancelAll()

If you're targeting API 24+ stopForeground(Service.STOP_FOREGROUND_REMOVE) or stopForeground(true)

Also you should probably look into onTrimMemory() and onLowMemory() which are function called when the OS destroy your service.

Wall answered 3/12, 2019 at 10:0 Comment(0)
S
0

Just use

stopForeground(true)

When your work will complete.It will destroy foreground notification.

Synopsis answered 27/3, 2020 at 9:58 Comment(0)
U
-2

Most likely you are not stopping your service

Universality answered 13/9, 2012 at 6:44 Comment(5)
I m stopping service and this is works fine in that case. But when my service is destroyed by android OS()(may be on low memory or something else) then how to remove notificationBehrens
@Behrens Why do you think onDestroy won't be called in this case?Universality
I have this problem when android system automatically destroy service.Behrens
@Behrens Documentation says onDestroy will be called in such case. I've never checked that out though.Universality
But onDestroy() not called in this case immediately (May be called after some time) so notification not removedBehrens

© 2022 - 2024 — McMap. All rights reserved.