Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove notification when service destroyed by android OS

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?

like image 537
user1041858 Avatar asked Sep 13 '12 06:09

user1041858


1 Answers

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

@Override
public void onDestroy() 
{
    nm.cancel(R.string.service_started);
    super.onDestroy();
}
like image 140
Tomáš Poráč Avatar answered Sep 20 '22 16:09

Tomáš Poráč