1. 程式人生 > >關於Android中Service的手動、自動以及其在特殊條件下的重啟

關於Android中Service的手動、自動以及其在特殊條件下的重啟

上一篇部落格有說到Service之間的守護問題。

接著這個Sevice的守護,我們可以做一些事。例如重啟。看到重啟你是不是就會想到Service自身來重啟呢?很遺憾,Service不能在kill(ondestory)掉自己之後又重新onstart,所以我們要人為地為其進行重啟,這裡就要利用上一部落格中的Service之間的守護問題了,其實都是很簡單和比較常規的做法。下面從第一個手動重啟開始。

1. 手動重啟Service:

核心程式碼:

Intent killOneIntent = new Intent();
killOneIntent.setAction("com.example.servicedemo.ServiceTwo");
MainActivity.this.stopService(killOneIntent);
這裡有Action需要在Manifest配置檔案中新增,如下:
<service
            android:name="ServiceTwo"
            android:process=":remote" >
            <intent-filter>
                <action android:name="com.example.servicedemo.ServiceTwo" />
            </intent-filter>
        </service>

2. 自動重啟Service:

核心程式碼:

Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                	// 每隔10秒重啟一次當前Service
                	if ((System.currentTimeMillis() / 1000) % 10 == 0) {
						stopSelf();
					}
                	
                    boolean b = MainActivity.isServiceWorked(ServiceTwo.this, "com.example.servicedemo.ServiceOne");
                    if(!b) {
                        Intent service = new Intent(ServiceTwo.this, ServiceOne.class);
                        startService(service);
                    }
                }
            };
            timer.schedule(task, 0, 1000);
        }
    });
在這裡我們做的重啟條件是每10秒重啟一次,所以我們需要開啟一個執行緒來進行讀秒,如果到了10秒,就“重啟”。這裡筆者做一件偷懶的事,對讀秒的演算法只是去獲取系統時間,並對其取餘,這樣的結果就是在於最初的10秒可能不足,當然改善的方法有很多。筆者這裡不作演示。

3. 特殊條件下的重啟:

核心程式碼:

class ScreenBroadcastReceiver extends BroadcastReceiver {
    	
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String intentActionString = intent.getAction();
                if (intentActionString.equals(Intent.ACTION_SCREEN_ON)) { // 開屏
                	Log.e("screenon" + TAG, "----------------------- on!");
                } else if (intentActionString.equals(Intent.ACTION_SCREEN_OFF)) { // 鎖屏
                	Log.e("screenon" + TAG, "----------------------- off!");
                	stopSelf();
                } else if (intentActionString.equals(Intent.ACTION_USER_PRESENT)) { // 解鎖
                	Log.e("screenon" + TAG, "----------------------- unlock!");
                }
            } catch (Exception e) {
            	e.printStackTrace();
            }
        }
    }
這裡用到的是監測螢幕開屏、關屏狀態。(其實這裡的方法和第二種自啟是同一回事。)
如果沒有看我上一篇部落格,而且對Service的重啟這一塊不是很瞭解的朋友們,可能就會問一個題,這裡的都對Service進行stop啊,沒有restart,難道Service的stop就是restart,其實不是的。感興趣的朋友可以看看我的上一部落格《Android中利用服務來守護程序》。