How to detect app removed from the recent list?

后端 未结 3 516
忘掉有多难
忘掉有多难 2020-11-29 09:22

I\'m working on a music app, and I want stop the service when user removes the application from the recent list and not when the first activity is destroyed(because when use

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 10:03

    I want stop the service when user removes the application from the recent list.

    Yes, you can either do that using stopWithTask flag as true for Service in Manifest file.

    Example:

    
    

    OR

    If you need event of application being removed from recent list, and do something before stopping service, you can use this:

    
    

    So your service's method onTaskRemoved will be called. (Remember, it won't be called if you set stopWithTask to true).

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

    Hope this helps.

提交回复
热议问题