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?

Molly
  • 1,887
  • 3
  • 17
  • 34
user1041858
  • 947
  • 2
  • 15
  • 32

5 Answers5

1

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

@Override
public void onDestroy() 
{
    nm.cancel(R.string.service_started);
    super.onDestroy();
}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
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));
Rajal
  • 634
  • 9
  • 21
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.

Biscuit
  • 4,840
  • 4
  • 26
  • 54
0

Just use

stopForeground(true)

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

Het Thummar
  • 41
  • 1
  • 4
-2

Most likely you are not stopping your service

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158