终止应用程序后保持后台服务运行 [英] Keep background service running after killing an application

查看:412
本文介绍了终止应用程序后保持后台服务运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开发了一个运行后台服务的android应用程序,即使该应用程序被用户杀死或出于某种原因,我仍需要该服务保持运行.我已经实现了该服务,并在onStartCommand方法中添加了返回START_STICKY,如下所示:

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;
}

我也像这样在AndroidManifest.xml中定义了服务:

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>

我注意到,在旧的android版本(例如android 4.4.2)上,它可以正常工作并且服务仍然有效,但是在某些具有android 6.0的设备上,它无法正常工作.设备是华为,

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,

-设置->应用-> (我的APP)->电池

-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?

推荐答案

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

 android:isolatedProcess="true"

 android:stopWithTask="false"

或同时使用

START_STICKY.

通过使用android:stopWithTask="false",即使应用被破坏,也无法关闭任务

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

例如:

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

这篇关于终止应用程序后保持后台服务运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆