Android system killed my service when I clear all recent app

前端 未结 5 2249
北海茫月
北海茫月 2020-12-13 10:39

I already using startforeground() at my Service, but Android keeps killing my Service when I clear all the recent apps.

Here\'

5条回答
  •  自闭症患者
    2020-12-13 11:41

    A long running service needs the following to make it less likely to be terminated:

    1. Return START_STICKY from onStartCommand(). With this, system will re-start the service even if it has to be stopped for resources limitations.

    2. When the service is not bound to any UI component (e.g an Activity), The service must go in foreground mode by showing a foreground notification. Foreground services are less likely to be terminated by system.

    3. Set the attribute "stopWithTask"=false in corresponding tag of manifest file.

    Also, note that devices from some manufacturers will terminate services even with above properties due to customization:

    1. Custom task managers.
    2. Battery saving features that can prohibit non-system services.

    Some application services do need to stay in background and have to be aggressively kept alive. Though this method is not recommended, but following steps can be done:

    1. Add triggers for service start : Such as Boot Complete, and Network Connected broadcasts.

    2. If service receives intents/broadcasts FLAG_RECEIVER_FOREGROUND in the intent.

    3. An extreme resort is to manually schedule a pending intent for service restart, with AlarmManager, when onTaskRemoved() is called.

    Also, see:

    1. START_STICKY does not work on Android KitKat

提交回复
热议问题