我开发了一个运行后台服务的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 的设备上,它无法工作。设备是华为,
-设置->应用程序->(我的应用程序)->电池
当我将此权限切换为打开时,我发现“屏幕关闭后继续运行”权限,它开始按我想要的方式工作。我怎样才能向我的应用程序授予此权限或其他权限,这样该服务就不会被终止?
开发者文档 https://developer.android.com/guide/topics/manifest/service-element.html#isolated说你可以通过使用以下属性来实现此行为:
android:isolatedProcess="true"
OR
android:stopWithTask="false"
或同时使用
START_STICKY
如果资源稀缺,就会被忽略。
通过使用android:stopWithTask="false"
即使应用程序被破坏也不允许任务关闭
eg:
<service
android:name=".ServiceName"
android:process=":MYPROCESS"
android:isolatedProcess="true"
android:stopWithTask="false">
<intent-filter>
<action android:name="PackageName.ServiceName" />
</intent-filter>
</service>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)