当我清除所有最近的应用程序时,Android系统终止了我的服务 [英] Android system killed my service when I clear all recent app
问题描述
我已经在Service
上使用了startforeground()
,但是当我清除所有最新的应用程序时,Android仍然会杀死我的Service
.
I already using startforeground()
at my Service
, but Android keeps killing my Service
when I clear all the recent apps.
这是我的服务代码:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Text")
.setTicker("Text")
.setContentText("Text")
.setSmallIcon(R.drawable.icon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.icon))
.build();
startForeground(100, notification);
return START_STICKY;
}
我用这段代码做错什么了吗?
Is there something wrong I did with this code?
推荐答案
长期运行的服务需要执行以下操作,以使其不太可能被终止:
A long running service needs the following to make it less likely to be terminated:
-
从
onStartCommand()
返回START_STICKY
.这样,即使由于资源限制而不得不停止服务,系统也会重新启动该服务.
Return
START_STICKY
fromonStartCommand()
. With this, system will re-start the service even if it has to be stopped for resources limitations.
当服务未绑定到任何UI组件(例如,活动)时,该服务必须通过显示前台通知而进入前台模式.前台服务不太可能被系统终止.
When the service is not bound to any UI component (e.g an Activity), The service must go in foreground mode by showing a foreground notification. Foreground services are less likely to be terminated by system.
在以下位置设置属性 "stopWithTask"=false
清单文件的相应<service>
标记.
Set the attribute "stopWithTask"=false
in corresponding <service>
tag of manifest file.
另外,请注意,某些制造商的设备将因定制而终止具有上述属性的服务:
Also, note that devices from some manufacturers will terminate services even with above properties due to customization:
- 自定义任务管理器.
- 省电功能,可以禁止非系统服务.
某些应用程序服务确实需要留在后台,并且必须积极地保持活动状态.尽管不建议使用此方法,但是可以执行以下步骤:
Some application services do need to stay in background and have to be aggressively kept alive. Though this method is not recommended, but following steps can be done:
-
添加用于启动服务的触发器:例如启动完成"和网络连接"广播.
Add triggers for service start : Such as Boot Complete, and Network Connected broadcasts.
如果服务接收到意图/广播 FLAG_RECEIVER_FOREGROUND
出于意图.
If service receives intents/broadcasts FLAG_RECEIVER_FOREGROUND
in the intent.
一个极端的方法是手动安排待处理的服务意图,并在AlarmManager
时重新启动onTaskRemoved()
被调用.
An extreme resort is to manually schedule a pending intent for service restart, with AlarmManager
, when onTaskRemoved()
is called.
另外,请参阅:
这篇关于当我清除所有最近的应用程序时,Android系统终止了我的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!