Android Service 监测是否被kill

广播

  • Intent.ACTION_TIME_TICK

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。

@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);
            }
        }
    }

获取的是正在运行的服务 用我们的服务去比较

你可能感兴趣的:(Android Service 监测是否被kill)