关于Android中Service的手动、自动以及其在特殊条件下的重启
生活随笔
收集整理的這篇文章主要介紹了
关于Android中Service的手动、自动以及其在特殊条件下的重启
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
上一篇博客有說(shuō)到Service之間的守護(hù)問(wèn)題。
博客地址:http://blog.csdn.net/lemon_tree12138/article/details/40322887
接著這個(gè)Sevice的守護(hù),我們可以做一些事。例如重啟。看到重啟你是不是就會(huì)想到Service自身來(lái)重啟呢?很遺憾,Service不能在kill(ondestory)掉自己之后又重新onstart,所以我們要人為地為其進(jìn)行重啟,這里就要利用上一博客中的Service之間的守護(hù)問(wèn)題了,其實(shí)都是很簡(jiǎn)單和比較常規(guī)的做法。下面從第一個(gè)手動(dòng)重啟開(kāi)始。
1. 手動(dòng)重啟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. 自動(dòng)重啟Service:
核心代碼:
Thread thread = new Thread(new Runnable() {@Overridepublic void run() {Timer timer = new Timer();TimerTask task = new TimerTask() {@Overridepublic void run() {// 每隔10秒重啟一次當(dāng)前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秒重啟一次,所以我們需要開(kāi)啟一個(gè)線程來(lái)進(jìn)行讀秒,如果到了10秒,就“重啟”。這里筆者做一件偷懶的事,對(duì)讀秒的算法只是去獲取系統(tǒng)時(shí)間,并對(duì)其取余,這樣的結(jié)果就是在于最初的10秒可能不足,當(dāng)然改善的方法有很多。筆者這里不作演示。
3. 特殊條件下的重啟:
核心代碼:
class ScreenBroadcastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {try {String intentActionString = intent.getAction();if (intentActionString.equals(Intent.ACTION_SCREEN_ON)) { // 開(kāi)屏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();}}} 這里用到的是監(jiān)測(cè)屏幕開(kāi)屏、關(guān)屏狀態(tài)。(其實(shí)這里的方法和第二種自啟是同一回事。)
如果沒(méi)有看我上一篇博客,而且對(duì)Service的重啟這一塊不是很了解的朋友們,可能就會(huì)問(wèn)一個(gè)題,這里的都對(duì)Service進(jìn)行stop啊,沒(méi)有restart,難道Service的stop就是restart,其實(shí)不是的。感興趣的朋友可以看看我的上一博客《Android中利用服務(wù)來(lái)守護(hù)進(jìn)程》。
工程連接:http://download.csdn.net/detail/u013761665/8129761
總結(jié)
以上是生活随笔為你收集整理的关于Android中Service的手动、自动以及其在特殊条件下的重启的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Android中利用服务来守护进程
- 下一篇: 设置Eclipse中的Courier N