How to properly stop a foreground service?

后端 未结 2 1449
逝去的感伤
逝去的感伤 2021-01-12 22:17

I use startForeground to make my service \"persist\" in background and not be killed by the OS.
I remove the service in the main activity onDestroy method by calling sto

2条回答
  •  一向
    一向 (楼主)
    2021-01-12 22:28

    if you want to stop your service when you are clearing your application from the recent task, you have to define an attribute stopWithTask for service in the manifest file like this as shown below

      
    

    then you can override onTaskRemoved method in the service , this will be called when the application's task is cleared

    @Override
        public void onTaskRemoved(Intent rootIntent) {
            System.out.println("onTaskRemoved called");
            super.onTaskRemoved(rootIntent);
            //do something you want
            //stop service
            this.stopSelf();
        }
    

提交回复
热议问题