Destroy the foreground notification when the service is killed

I have a front-end service to download some content from the Internet.

Unfortunately, due to the error reported here , my service was killed when the recipient received the broadcast in my service, but the notification will not be killed, and I saw after entering my logcat:

I/ActivityManager(449): Killing 11073:my-package-name/u0a102 (adj 0): remove task

Is there a way to destroy the foreground notification when its parent service is killed by the OS?

+4
source share
6 answers

Use stopForeground:

@Override
public void onDestroy() {
 // as the bug seems to exists for android 4.4
 if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT)
 {
    stopForeground(true);
 }
  super.onDestroy();
}

or

public void onTaskRemoved (Intent rootIntent)
{
 // as the bug seems to exists for android 4.4
 if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT)
 {
   stopForeground(true);
 }
}
+1
source

(, Handler), :

public static boolean isMyServiceRunning(Context context) {
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))                           {
        if (MyService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

.

private static final int DEALY = 10000;
private Handler handler = new Handler();

...
handler.postDelayed(ensureSericeIsRunning, DELAY);
...

private Runnable ensureSericeIsRunning = new Runnable() {

    @Override
    public void run() {
        if (!isMyServiceRunning(getActivity())){
            //shut down notification
        } else {
            handler.postDelayed(ensureSericeIsRunning, DELAY);
        }
    }
};
+1

onStop onDestroy . P.S , , api 14 , START_STICKY, , , .

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}
0

use onDestroy(). Even the documentation says that it is not guaranteed that it is called, I tested several times, and the only cases that it does not cause are when the system kills the process, but by this moment your notification will be killed, so this is normal.

0
source

End of service deletes the foreground notification.

@Override
public void onDestroy() {
    // mycleanup first
    stopForeground(true);
    super.onDestroy();
}
0
source
-1
source

Source: https://habr.com/ru/post/1536405/


All Articles