Keep background service running after killing an a

2019-04-16 19:25发布

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?

enter image description here

1条回答
相关推荐>>
2楼-- · 2019-04-16 20:08

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>
查看更多
登录 后发表回答