java使后台服务始终运行,并且从不停止运行或系统破坏它
您好,我正在运行后台服务来检查我的服务器是否有新数据
但是如果我关闭了应用程序,后台服务也会死掉。 如果我在上面运行后台服务;在进程上,系统在运行几次后将其杀死
清单
<service
安卓:name=".backgroundSerive"
安卓:enabled="true"
安卓:exported="false"/>
选择2
<service
安卓:name=".backgroundSerive"
安卓:process=":my_process"
安卓:enabled="true"
安卓:exported="false"/>
维护活动-启动服务
Intent i = new Intent(this, backgroundSerive.class );
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(i);
服务
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...start runnable
return START_STICKY;
}
I try both option, The service keeps getting killed.
任何建议。使我的服务器始终运行。 多谢各位
# 1 楼答案
您需要从服务内部调用
startForeground()
,以降低Android实际杀死它的可能性。请查看此sample以获取示例实现# 2 楼答案
startForeground函数将服务发送到前台,因此android系统将此操作视为前台任务。死亡的可能性很小
如果您选择服务销毁操作作为START\u STICKY,它将被销毁,但在它销毁之后,应该使用null意图重新初始化它
你可以考虑对这种事件使用警报。 由于警报在内部进程中运行,因此它们减少了应用程序开销,但也提供了重复检查