暮鼓集 行走集
原作于2014年02月15日
1.Service是可以被系统回收的
Android设计有Memory的回收策略,在可分配内存少于某个值时会启动回收。与前台UI一样,Service也可以被回收。
在STS此前版本,Service启动一个Thread,并使用sleep来等待,这样更容易被系统回收掉。
有如下改善方法:
(1) 在AndroidManifest.xml中给Application增加android:persistent=true 这一项的意思是指明Whether or not the application should remain running at all times。 根据网上的资料,只有App置于system/apps目录下,即作为系统应用时,这一项才会生效。 通常,这种做法是应避免的,只有极少数程序才需要一直运行。
(2) 提高App的优先级 AndroidManifest.xml中给Service增加intent-filter android:priority=”1000”。
(3) 在Serivce启动时调用startForeground 这也可以提高优先级。
(4) OnCreate返回START_STICKY 这样做,当Service被回收后,系统稍后会重新运行。
2.不要使用Sleep进行长时间定时,要使用AlarmManager代替
有两个问题:一是容易被系统回收,上面已经提到;二是进入系统进入节电模式休眠后sleep的定时也不会执行了。
StackOverflow上的一段: Services run on the main thread. If you want to offload processing, you have to start a separate thread. Have a look at IntentService, it does this by default. On another note, having an infinitely running service with sleep() might not a good idea. For scheduled processing, you might want to use AlarmManager.
AlarmManager独立于App存在,不受系统休眠的影响,它的定时是非常稳定的。
3.BroadcastReceiver的生命周期极短
BroadcastReceiver是Android App的入口之一,一旦接收到Broadcast Intent,App就会启动。
但是BroadReceiver生命周期极短,它在主线程中运行,执行完毕,如果App没有其他任务,就退出了。
在其中不要执行长时间的操作,这会导致ANR。
4.WakeLock防止Service运行时系统进入休眠
使用WakeLock.require来请求阻止,WakeLock.release来释放。