关于Android中Service的手动、自动以及其在特殊条件下的重启
生活随笔
收集整理的這篇文章主要介紹了
关于Android中Service的手动、自动以及其在特殊条件下的重启
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
上一篇博客有說到Service之間的守護問題。
博客地址:http://blog.csdn.net/lemon_tree12138/article/details/40322887
接著這個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配置文件中添加,如下:
<serviceandroid: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() {@Overridepublic void run() {Timer timer = new Timer();TimerTask task = new TimerTask() {@Overridepublic void run() {// 每隔10秒重啟一次當前Serviceif ((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 {@Overridepublic 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中利用服務來守護進程》。
工程連接:http://download.csdn.net/detail/u013761665/8129761
總結
以上是生活随笔為你收集整理的关于Android中Service的手动、自动以及其在特殊条件下的重启的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android中利用服务来守护进程
- 下一篇: 设置Eclipse中的Courier N