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);
    }
posted @ 2012-12-27 09:51 我不是神 阅读(498) 评论(1) 推荐(0) 编辑
摘要: usingSystem.Text.RegularExpressions; strings = (12345678901234567890.123456789).ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");stringd = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[ 阅读全文
posted @ 2012-08-08 10:36 我不是神 阅读(307) 评论(0) 推荐(0) 编辑
摘要: <script type="text/javascript">var Tree = Ext.tree;var tree = null;Ext.onReady(function(){ tree = new Tree.TreePanel({ el:'tree-div', onlyLeafCheckable:false, rootVisible: true, autoScroll:true,... 阅读全文
posted @ 2008-10-16 08:50 我不是神 阅读(1632) 评论(0) 推荐(0) 编辑
摘要: 很好的正则表达式教程 阅读全文
posted @ 2006-09-23 08:45 我不是神 阅读(483) 评论(0) 推荐(0) 编辑
点击右上角即可分享
微信分享提示