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