如何让Android的service一直在后台运行?

发布时间:2020-08-07 11:30:02 作者:山有木xi
来源:ITPUB博客 阅读:725

Service是Android四大组件之一,同时也是四大组件中和Activity最相似的组件,都代表着可执行的程序,他们的区别在于Service一直在后台运行,没有用户界面,一旦被启动就和Activiy一样拥有生命周期,一般来说,需要显示界面则使用Activity,不需要则可以选择Service

Activity的生命周期在于用户打开与关闭,从用户打开程序到用户关闭程序之间存在,那么Service呢?他的生命周期在于什么,是否也是在用户的打开与关闭,Service能否一直存在于后台

一般情况下,只有系统自带的应用或者厂商定制的应用拥有比较高的优先级能够保持后台服务一直运行,也就是,可以通过root后给予相应高的权限,理论上可以做到一直存在于后台的服务,那么对于未root的系统呢?

这时候就需要一些小技巧和方法

“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.)”

也就是说,其实第四种方法更为方便并且被官方所推荐

startForeground 的使用也是很简单的,只需要修改onCreat的内容,在其中创建Notification对象,然后用调用 startForeground(1, Notification)即可实现

推荐阅读:
  1. android的service
  2. android的Service的实例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android service 一直

上一篇:相对路径和绝对路径有哪些区别

下一篇:电脑计算器如何计算二进制

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》