全心思齐网

怎么设置让一个软件一直在后台运行?

android 一直运行的后台服务是不存在的,而且也不是最佳实践,因为一直运行的后台服务会耗费大量系统资源,影响其他程序的响应从而影响到用户体验。
题主问的是如何让后台服务一直运行,我认为只有系统自带的应用或者定制的系统应用才可以有这么高的优先级可以保持后台服务一直运行。如果是在非root的系统上的普通应用,只能是通过一些方法,让用户觉着后台服务一直运行。比如,监听开机事件,显式地启动后台服务;启动后台服务后给它设置“前台运行”的优先级;定时任务来检查后台服务是否在运行,不运行的话重新启动它。
可以考虑使用如下几种方案来达到一直运行的效果。
1. 调用startForeground方法,

android: Service vs SingleTop Activity moved to background


2. 使用AlarmManager 发送定时任务 :

Diamonds Are Forever. Services Are Not.



更极端的例子,如果应用被干掉了,定时任务(AlarmManager)这种方法确实不管用了,但是可以考虑给后台服务设置“前台”运行的优先级这种方法。比如音乐播放器,在启动播放服务后,通知栏会显示一个播放进度的通知条,这个通知条是必须的,因为通过它才能使后台服务获取到“前台”运行的优先级从而避免被系统干掉。这种做法也是官方推荐的做法。
下面是官方文档中的一些具体说明:

说明一


A started service can use the

startForeground(int, Notification)

API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory. (It is still theoretically possible for the service to be killed under extreme memory pressure from the current foreground application, but in practice this should not be a concern.)

说明二


Service | Android Developers

(int, android.app.Notification)

Make this service run in the foreground, supplying the ongoing notification to be shown to the user while in this state. By default services are background, meaning that if the system needs to kill them to reclaim more memory (such as to display a large page in a web browser), they can be killed without too much harm. You can set this flag if killing your service would be disruptive to the user, such as if your service is performing background music playback, so the user would notice if their music stopped playing.

其他参考资料

使用startForeground让android服务前台运行


android - startForeground() without showing notification

匿名回答于2023-10-21 03:06:01


相关知识问答