400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

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

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)即可实现


本文标题:如何让Android的service一直在后台运行?
网址分享:http://www.bluegullmedia.com/article/gjshjj.html

其他资讯

让你的专属顾问为你服务

0.0420s