Keep background service running after killing an application

天大地大妈咪最大 提交于 2019-12-22 01:08:10

问题


I have developed an android application which runs background service, I need the service to stay alive even if the application is killed by user or for some reason. I have implemented the service and add return START_STICKY in onStartCommand method like this:

public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);

    Log.d("my_state","On start command");

    return START_STICKY;
}

also I defined the service in AndroidManifest.xml like this:

    <service android:name=".MeterDistanceCalcService"
        android:exported="true"
        android:enabled="true"
        android:stopWithTask="false"
        >

        <intent-filter>
            <action android:name="LONGRUNSERVICE" />
        </intent-filter>

    </service>

I noticed that on old android versions, like android 4.4.2, it works fine and the services stays alive, but on some devices which has android 6.0, it does not work. The device is Huawei,

-Settings -> apps -> (MY APP) -> Battary

I found permission "Keep running after screen off" when I toggle this permission to on, it start working as I want. how can I give this permission or whatever to my application, so the service will not be killed?


回答1:


Developer's documentation says you can achieve this behaviour by using the attribute:

 android:isolatedProcess="true"

OR

 android:stopWithTask="false"

OR Using Both

START_STICKY will be ignored if the resources are scare.

By using android:stopWithTask="false" wont allow tasks to be closed even app is destroyed

eg:

<service
        android:name=".ServiceName"
        android:process=":MYPROCESS"
        android:isolatedProcess="true"
        android:stopWithTask="false">
            <intent-filter>
                 <action android:name="PackageName.ServiceName" />
            </intent-filter>
  </service>


来源:https://stackoverflow.com/questions/47812550/keep-background-service-running-after-killing-an-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!