Android SERVICE后台服务进程的自启动和保持

移动开发 Android
Service组件在android开发中经常遇到,其经常作为后台服务,需要始终保持运行,负责处理一些必要(见不得人)的任务。

Service组件在android开发中经常遇到,其经常作为后台服务,需要始终保持运行,负责处理一些必要(见不得人)的任务。而一些安全软件,如360等,会有结束进程的功能,如果不做Service的保持,就会被其杀掉。

如何保持Service的运行状态是现在要说明的,核心就是利用ANDROID的系统广播,这一不会被其他软件影响的常驻程序触发自己的程序检查Service的运行状态,如果被杀掉,就再起来。

我利用的系统广播是Intent.ACTION_TIME_TICK,这个广播每分钟发送一次,我们可以每分钟检查一次Service的运行状态,如果已经被结束了,就重新启动Service。

下边就是具体的代码和注意事项了:

1、 Intent.ACTION_TIME_TICK的使用

我们知道广播的注册有静态注册和动态注册,但此系统广播只能通过动态注册的方式使用。即你不能通过在manifest.xml里注册的方式接收到这个广播,只能在代码里通过registerReceiver()方法注册。

在ThisApp extends Application 里注册广播:

  1. IntentFilter filter = newIntentFilter(Intent.ACTION_TIME_TICK); 
  2. MyBroadcastReceiver receiver = new MyBroadcastReceiver(); 
  3. registerReceiver(receiver, filter); 

在广播接收器MyBroadcastReceiver extends BroadcastReceiver的onReceive里

  1. if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) { 
  2.   
  3. //检查Service状态 
  4.   

2、Service的检查与启动

  1. boolean isServiceRunning = false
  2. ActivityManager manager = (ActivityManager)ThisApp.getContext().getSystemService(Context.ACTIVITY_SERVICE); 
  3. for (RunningServiceInfo service :manager.getRunningServices(Integer.MAX_VALUE)) { 
  4.   if("so.xxxx.WidgetUpdateService".equals(service.service.getClassName())) 
  5.        //Service的类名 
  6.     { 
  7.       isServiceRunning = true
  8.     } 
  9.   
  10.  } 
  11. if (!isServiceRunning) { 
  12.     Intent i = new Intent(context, WidgetUpdateService.class); 
  13.        context.startService(i); 

另一个话题,Service的开机启动。

实现和上边的类似,也是通过监控开机的系统广播来启动Service。但其实你做了上边的检查也就不会做开机启动了,因为过一两分钟就会通过上边的程序启动Service了。代码如下:

  1. if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { 
  2.   Intent i = new Intent(context, LogService.class); 
  3.     context.startService(i); 
  4.     } 
责任编辑:徐川 来源: eoeAndroid
相关推荐

2012-10-10 12:36:44

打印机故障

2011-08-25 09:32:30

Visual Stud

2013-01-18 17:30:32

Linux系统

2023-05-30 07:38:02

2023-05-31 07:54:11

2017-06-23 15:01:10

2009-08-14 17:04:19

Windows后台服务

2018-12-13 09:27:31

后台服务架构

2021-08-06 22:41:53

Windows微软自启动

2021-08-06 12:47:22

Windows 10Windows微软

2009-11-11 10:26:02

LinuxOracle监听自启动

2016-09-23 15:50:25

Windows 7VirtualBox虚拟机

2012-12-25 16:58:36

Android服务

2011-03-04 09:55:40

RIM黑莓Android

2009-04-22 17:14:11

LinuxSAMBA服务

2010-01-27 18:00:57

Android开机自启

2009-04-30 09:02:53

AcerAndroid开发

2010-01-04 10:05:18

linux挂载windows

2010-05-05 16:30:25

Oracle后台进程

2010-10-29 15:54:13

Oracle后台进程
点赞
收藏

51CTO技术栈公众号