Android Service后台服务进程意外被kill掉之后如何重启

Service组件在android开发中经常用到,经常作为后台服务,需要一直保持运行,负责处理一些不必展示的任务。而一些安全软件,会有结束进程的功能,如果不做Service的保持,就会被其杀掉。

那么如何保持Service的运行状态,核心就是利用ANDROID的系统广播,这一不会被其他软件影响的常驻程序触发自己的程序检查Service的运行状态,如果被杀掉,就再起来。
在众多的Intent的action动作中,Intent.ACTION_TIME_TICK是比较特殊的一个,根据SDK描述:

Broadcast Action: The current time has changed. Sent every minute. You can not receive this through components declared in manifests, only by exlicitly registering for it withContext.registerReceiver()

意思是说这个广播动作是以每分钟一次的形式发送。但你不能通过在manifest.xml里注册的方式接收到这个广播,只能在代码里通过registerReceiver()方法注册。根据此我们可以每分钟检查一次Service的运行状态,如果已经被结束了,就重新启动Service。
所以只能通过动态注册了,若要持久 我们索性在application里面注册

IntentFilter filter=new IntentFilter(Intent.ACTION_TIME_TICK); 
        registerReceiver(receiver, filter); 

在onReceive中

public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {

        }
    }

OK 下面我们看下测试代码的核心部位 也就是检测服务是否启动

@Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
            // 检查Service状态
            boolean isServiceRunning = false;

            ActivityManager manager = (ActivityManager) app
                    .getApplicationContext().getSystemService(
                            Context.ACTIVITY_SERVICE);
            //获取正在运行的服务去比较
            for (RunningServiceInfo service : manager
                    .getRunningServices(Integer.MAX_VALUE)) {
                Log.i("Running", service.service.getClassName());
                if ("com.example.android_service.MyService"
                        .equals(service.service.getClassName()))
                // Service的类名
                {
                    isServiceRunning = true;
                }
            }
            Log.i("isRunning", isServiceRunning + "");
            if (!isServiceRunning) {
                Log.i("isRunningOK", isServiceRunning + "");
                Intent i = new Intent(context, MyService.class);
                app.getApplicationContext().startService(i);
            }
        }
    }

上面清楚的写明了逻辑 获取的是正在运行的服务 用我们的服务去比较如果没有就启动有的话就不用管了

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章