一.使用service来在后台常驻,好比,播放音乐、在activity中使用MediaPlay固然也能够直接播放音乐,程序退出了也能够继续播放,但为何使用service呢?由于service 存活能力强,能够长时间运行。android
二.提升service的存活能力。这里先说一下进程的优先级:前台进程>可见进程>服务进程>后台进程>空进程。.net
1.把服务设置成前台服务,这个功能要求发送一个通知显示在通知栏上面code
/** \* 将服务调至前台,提升优先级,减小服务被杀死的可能性 \* [@param](http://my.oschina.net/u/2303379) startId */ private void setForeground(int startId) { Notification notification = new Notification(); startForeground(startId, notification); } //取消服务发出的通知 musicService.stopForeground(true);
2.在Manifest里面 intentfilter 设置优先级 1000,最高的进程
好比it
<service android:name="cn.com.kuting.ktingservice.KtingMusicService" > <intent-filter android:priority="1000"></intent-filter> </service>
3.双进程保活,互相监听,挂了重启,比较恶心。
4.监听广播或者推送,服务若是挂了就去重启服务。 5.还有一些一像素,播放无声音乐的方法。io