Android中Service被杀时自动重启的方法

来源:互联网 发布:做彩票网络销售经历 编辑:程序博客网 时间:2024/05/16 23:59

    1、在Service中重写onStartCommand()方法,并返回START_STICKY;或者将该方法中的flags置为START_STICKY:

   

@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {return START_STICKY;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubLog.v("TrafficService","startCommand");flags = START_STICKY;return super.onStartCommand(intent, flags, startId);}


    2、在Service的onDestroy()方法中重启Service:

   

public void onDestroy() { Intent localIntent = new Intent();localIntent.setClass(this, MyService.class); //销毁时重新启动Servicethis.startService(localIntent);}


    3、如何实现一个不会被杀死的进程
    看Android的文档知道,当进程长期不活动,或系统需要资源时,会自动清理门户,杀死一些Service,和不可见的Activity等所在的进程。但是如果某个进程不想被杀死(如数据缓存进程,或状态监控进程,或远程服务进程),则应该在AndroidManifest.xml文件的<application>中添加

    android:persistent="true"

    切记,这个不可滥用,系统中用这个的service,app一多,整个系统就完蛋了。
    目前系统中有phone等非常有限的、必须一直活着的应用在试用。

    4、提升service优先级的方法
    Android系统对于内存管理有自己的一套方法,为了保障系统有序稳定的运信,系统内部会自动分配,控制程序的内存使用。当系统觉得当前的资源非常有限的时候,为了保证一些优先级高的程序能运行,就会杀掉一些他认为不重要的程序或者服务来释放内存。这样就能保证真正对用户有用的程序仍然再运行。如果你的Service碰上了这种情况,多半会先被杀掉。但如果你增加Service的优先级就能让他多留一会,我们可以用setForeground(true)来设置Service的优先级。

    为什么是foreground?默认启动的Service是被标记为background,当前运行的Activity一般被标记为foreground,也就是说你给Service设置了foreground那么他就和正在运行的Activity类似优先级得到了一定的提高。当然这并不能保证你得Service永远不被杀掉,只是提高了它的优先级。

    从Android 1.5开始,一个已启动的service可以调用startForeground(int, Notification)将service置为foreground状态,调用stopForeground(boolean)将service置为background状态。

    我们会在调用startForeground(int, Notification)传入参数notification,它会在状态栏里显示正在进行的foreground service。background service不会在状态栏里显示。

    5、如何防止Android应用中的Service被系统回?
    对于Service被系统回收,一般做法是通过提高优先级来解决:在AndroidManifest.xml文件中在intent-filter中通过android:priority = "1000"这个属性设置最高优先级(1000是最高值,数字越小则优先级越低,同时适用于广播)。

    原文链接:http://www.cnblogs.com/ylligang/articles/2665181.html

原创粉丝点击