Service组件在android开发中经常遇到,其经常作为后台服务,需要始终保持运行,负责处理一些必要(见不得人)的任务。而一些安全软件,如垃圾360等,会有结束进程的功能,如果不做Service的保持,就会被其杀掉。
如何保持Service的运行状态是现在要说明的,核心就是利用ANDROID的系统广播,这一不会被其他软件影响的常驻程序触发自己的程序检查Service的运行状态,如果被杀掉,就再起来。
我利用的系统广播是Intent.ACTION_TIME_TICK,这个广播每分钟发送一次,我们可以每分钟检查一次Service的运行状态,如果已经被结束了,就重新启动Service。
下边就是具体的代码和注意事项了:
1、 Intent.ACTION_TIME_TICK的使用
我们知道广播的注册有静态注册和动态注册,但此系统广播只能通过动态注册的方式使用。即你不能通过在manifest.xml里注册的方式接收到这个广播,只能在代码里通过registerReceiver()方法注册。
在ThisApp extends Application 里注册广播
01
02
03
|
IntentFilter filter = newIntentFilter(Intent.ACTION_TIME_TICK); MyBroadcastReceiver receiver = new MyBroadcastReceiver(); registerReceiver(receiver, filter); |
在广播接收器MyBroadcastReceiver extends BroadcastReceiver的onReceive里
01
02
03
04
05
|
if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { //检查Service状态 } |
2、Service的检查与启动
01
02
03
04
05
06
07
08
09
10
11
12
13
14
|
boolean isServiceRunning = false ; ActivityManager manager = (ActivityManager)ThisApp.getContext().getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service :manager.getRunningServices(Integer.MAX_VALUE)) { if ( "so.xxxx.WidgetUpdateService" .equals(service.service.getClassName())) //Service的类名 { isServiceRunning = true ; } } if (!isServiceRunning) { Intent i = new Intent(context, WidgetUpdateService. class ); context.startService(i); } |
另一个话题,Service的开机启动。
实现和上边的类似,也是通过监控开机的系统广播来启动Service。但其实你做了上边的检查也就不会做开机启动了,因为过一两分钟就会通过上边的程序启动Service了。代码如下:
01
02
03
04
|
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { Intent i = new Intent(context, LogService. class ); context.startService(i); } |