Android SERVICE后臺(tái)服務(wù)進(jìn)程的自啟動(dòng)和保持
Service組件在android開(kāi)發(fā)中經(jīng)常遇到,其經(jīng)常作為后臺(tái)服務(wù),需要始終保持運(yùn)行,負(fù)責(zé)處理一些必要(見(jiàn)不得人)的任務(wù)。而一些安全軟件,如360等,會(huì)有結(jié)束進(jìn)程的功能,如果不做Service的保持,就會(huì)被其殺掉。
如何保持Service的運(yùn)行狀態(tài)是現(xiàn)在要說(shuō)明的,核心就是利用ANDROID的系統(tǒng)廣播,這一不會(huì)被其他軟件影響的常駐程序觸發(fā)自己的程序檢查Service的運(yùn)行狀態(tài),如果被殺掉,就再起來(lái)。
我利用的系統(tǒng)廣播是Intent.ACTION_TIME_TICK,這個(gè)廣播每分鐘發(fā)送一次,我們可以每分鐘檢查一次Service的運(yùn)行狀態(tài),如果已經(jīng)被結(jié)束了,就重新啟動(dòng)Service。
下邊就是具體的代碼和注意事項(xiàng)了:
1、 Intent.ACTION_TIME_TICK的使用
我們知道廣播的注冊(cè)有靜態(tài)注冊(cè)和動(dòng)態(tài)注冊(cè),但此系統(tǒng)廣播只能通過(guò)動(dòng)態(tài)注冊(cè)的方式使用。即你不能通過(guò)在manifest.xml里注冊(cè)的方式接收到這個(gè)廣播,只能在代碼里通過(guò)registerReceiver()方法注冊(cè)。
在ThisApp extends Application 里注冊(cè)廣播:
- IntentFilter filter = newIntentFilter(Intent.ACTION_TIME_TICK);
- MyBroadcastReceiver receiver = new MyBroadcastReceiver();
- registerReceiver(receiver, filter);
在廣播接收器MyBroadcastReceiver extends BroadcastReceiver的onReceive里
- if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
- //檢查Service狀態(tài)
- }
2、Service的檢查與啟動(dòng)
- 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的類(lèi)名
- {
- isServiceRunning = true;
- }
- }
- if (!isServiceRunning) {
- Intent i = new Intent(context, WidgetUpdateService.class);
- context.startService(i);
- }
另一個(gè)話(huà)題,Service的開(kāi)機(jī)啟動(dòng)。
實(shí)現(xiàn)和上邊的類(lèi)似,也是通過(guò)監(jiān)控開(kāi)機(jī)的系統(tǒng)廣播來(lái)啟動(dòng)Service。但其實(shí)你做了上邊的檢查也就不會(huì)做開(kāi)機(jī)啟動(dòng)了,因?yàn)檫^(guò)一兩分鐘就會(huì)通過(guò)上邊的程序啟動(dòng)Service了。代碼如下:
- if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
- Intent i = new Intent(context, LogService.class);
- context.startService(i);
- }