Service組件在android開發中經常用到,經常作爲後臺服務,需要一直保持運行,負責處理一些不必展示的任務。而一些安全軟件,會有結束進程的功能,如果不做Service的保持,就會被其殺掉。
那麼如何保持Service的運行狀態,核心就是利用ANDROID的系統廣播,這一不會被其他軟件影響的常駐程序觸發自己的程序檢查Service的運行狀態,如果被殺掉,就再起來。
在衆多的Intent的action動作中,Intent.ACTION_TIME_TICK是比較特殊的一個,根據SDK描述:
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。
所以只能通過動態註冊了,若要持久 我們索性在application裏面註冊
IntentFilter filter=new IntentFilter(Intent.ACTION_TIME_TICK);
registerReceiver(receiver, filter);
在onReceive中
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
}
}
OK 下面我們看下測試代碼的核心部位 也就是檢測服務是否啓動
@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);
}
}
}
上面清楚的寫明瞭邏輯 獲取的是正在運行的服務 用我們的服務去比較如果沒有就啓動有的話就不用管了