android 关于提高app的进程service优先级

来源:互联网 发布:qq邮箱pop端口 编辑:程序博客网 时间:2024/06/08 06:35

基本上大家都知道提高service优先级可以在很大程度上让你的service免于因为内存不足而被kill,当然系统只是在此时先把优先级低的kill掉,如果内存还是不够,也会把你的service干掉的。不过现在的机器不像几年前了,基本上不会发生那种情况。

先来看看网上常见的“错误”方法:

1.android:persistent=”true”

对第三方app无效,下面是官方说明
android:persistentWhether or not the application should remain running at all times — “true” if it should, and “false” if not. The default value is “false”. Applications should not normally set this flag; persistence mode is intended only for certain system applications.
另外这个方法如果使用在系统应用中有可能会出现某些平台出现不能读写外界存储,请注意。

2.onDestroy中重启service

service被系统杀死的时候并不一定会执行onDestroy,拿什么重启,而且如果是在服务中下载东西,被系统结束进程后及时再重新启动,需要处理的东西也比较麻烦,不推荐。

3.android:priority

<!-- 为了消去加上android:priority="1000"后出现的警告信息,可以设置android:exported属性,指示该服务是否能够被其他应用程序组件调用或跟它交互 --><service android:name="com.example.helloandroid.weatherforecast.service.UpdateWidgetService"         android:exported="false" > <!-- 为防止Service被系统回收,可以通过提高优先级解决,1000是最高优先级,数字越小,优先级越低 -->     <intent-filter android:priority="1000"></intent-filter></service>

这个方法我用了,但是没什么卵用,不知道是不是那个地方需要一起配合,希望了解的大神能帮忙解释一下。

4.setForeground

这个是有效的,但是网上有些例子却无效的原因是参数错误

让service免于非难的办法是提高它的重要性,在官方文档中已经说明进程有五个级别,其中前台进程最重要,所以最后被杀死。
进程的oom_adj值也就代表了它的优先级。oom_adj值越高代表该进程优先级越低:
1.前台进程( FOREGROUND_APP) 0
2.可视进程(VISIBLE_APP ) 1
3.次要服务进程(SECONDARY_SERVER ) 2
4.后台进程 (HIDDEN_APP) 7
5.内容供应节点(CONTENT_PROVIDER) 14
6.空进程(EMPTY_APP) 15
这里只说如何使用startForeground将service设置为前台进程
在service的onCreate中

Notification notification = new Notification();notification.flags = Notification.FLAG_ONGOING_EVENT;notification.flags |= Notification.FLAG_NO_CLEAR;notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;service.startForeground(1, notification);

上面的三个属性放到一起,值为0x62。

如果不需要一直存在的话
在service的onDestroy中加上 stopForeground(true); 不然一直占着资源也不太合适哈。

另外值得注意的是这个方法是在版本1.0以后的,强制和 notification 绑定,网上有的说 startForeground的第一个参数置为 0 就不显示通知栏了,我想说的是,如果置为0 ,这个方法就然并卵了,而且这样写完之后也不会出现通知栏。(亲测)

然后用命令查一下adb shell cat/proc/你的进程号/oom_adj 切到后台的程序果然变成了 1 有木有。

本文是根据http://www.2cto.com/kf/201406/311442.html 完善的。

0 0
原创粉丝点击