android开发之关于提高第三方app的service优先级(以及例举网上常见的错误方法)

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

 

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

 

1.android:persistent="true"

对第三方app无效,下面是官方说明

android:persistent
Whether 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

service根本没有这属性

 

4.setForeground

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

 

让service免于非难的办法是提高它的重要性,在官方文档中已经说明进程有五个级别,其中前台进程最重要,所以最后被杀死。

如何使之变成前台进程可以参阅官方文档。

http://developer.android.com/guide/components/processes-and-threads.html

http://su1216.iteye.com/blog/1591699

 

这里只说如何使用setForeground将service设置为前台进程


<span style="font-family:KaiTi_GB2312;font-size:18px;">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);  </span>

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

  1. /** 
  2.  * Bit to be bitwise-ored into the {@link #flags} field that should be 
  3.  * set if this notification is in reference to something that is ongoing, 
  4.  * like a phone call.  It should not be set if this notification is in 
  5.  * reference to something that happened at a particular point in time, 
  6.  * like a missed phone call. 
  7.  */  
  8. public static final int FLAG_ONGOING_EVENT      = 0x00000002;  
  9. /** 
  10.  * Bit to be bitwise-ored into the {@link #flags} field that should be 
  11.  * set if the notification should not be canceled when the user clicks 
  12.  * the Clear all button. 
  13.  */  
  14. public static final int FLAG_NO_CLEAR           = 0x00000020;  
  15.   
  16. /** 
  17.  * Bit to be bitwise-ored into the {@link #flags} field that should be 
  18.  * set if this notification represents a currently running service.  This 
  19.  * will normally be set for you by {@link Service#startForeground}. 
  20.  */  
  21. public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;  
最后,我们可以使用下面命令看看手机中的哪些应用这么干了,你在平时使用的时候是不是他们存活时间最长,最不容易被系统干掉
dumpsys notification  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值