【问题标题】:Keep background service running after killing an application杀死应用程序后保持后台服务运行
【发布时间】:2017-12-14 20:23:17
【问题描述】:

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

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 中定义了服务:

    <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 的设备上,它不起作用。设备是华为,

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

当我将此权限切换为打开时,我发现“屏幕关闭后继续运行”权限,它开始按我的意愿工作。我怎样才能向我的应用程序授予此权限或任何其他权限,这样服务就不会被杀死?

【问题讨论】:

标签: android background-service long-running-processes


【解决方案1】:

Developer's documentation 表示您可以通过使用属性来实现此行为:

 android:isolatedProcess="true"

 android:stopWithTask="false"

或者同时使用

如果资源紧张,START_STICKY 将被忽略。

通过使用android:stopWithTask="false" 将不允许关闭任务,即使应用程序被销毁

例如:

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

【讨论】:

  • “通过使用 android:stopWithTask="false" 即使应用程序被销毁也不允许关闭任务”是什么意思?我没有,你能澄清一下吗?
  • 将这些添加到清单中。看到这些后,服务将作为一项独立任务工作,即使应用程序被销毁,该服务也不会被销毁,直到手动停止服务或重新启动 fone
  • 当我添加属性 android:isolatedProcess="true" 服务没有启动。
  • 我设法运行了该服务,但现在的问题是,我无法读取 gps 位置,(LocationManager) getSystemService(Context.LOCATION_SERVICE);总是返回 null
  • 检查初始化
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 2015-08-12
  • 2018-03-08
  • 1970-01-01
  • 2014-07-08
相关资源
最近更新 更多