Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Service 進階用法:IntentService、生命週期、前台服務與常駐技巧

編輯:Android 開發實例

前言

上一篇我們談過 Service 的基礎操作,若還不熟悉這塊,建議先回頭複習。本文則要往更深處走,盤點 Service 在實務開發中必須留意的細節與進階玩法,並搭配範例逐一示範,最後同樣附上源碼下載。

本文涵蓋以下重點:

  1. IntentService 的使用
  2. Service 與 Thread 的差異
  3. Service 生命週期詳解
  4. 前台服務
  5. 服務資源被系統意外回收的處理辦法
  6. 打造不被銷毀的常駐服務

IntentService

別忘了,Service 依然跑在主線程之上。因此那些無法在主線程完成的任務,仍需另開工作線程處理;而耗時操作若直接丟在主線程執行,就會拖累整機的流暢度。面對這個問題,有兩條路可走:一是在 Service 主線程中自行開一條工作線程(開線程的寫法前面已談過,這裡不再重述);二就是採用 IntentService 這個便捷的父類,本文重點放在後者。

IntentService 是一個直接繼承自 Service 的服務基類,能在需要時以異步行為處理請求。要讓 IntentService 啟動並異步執行,必須實作它的抽象方法 onHandleIntent(Intent intent),在這個方法裡,你會拿到傳入的 Intent 物件,並在其中完成異步邏輯。由於它同樣繼承自 Service,因此 Service 的聲明週期方法在此照樣適用,呼叫方仍可透過 Context.startService(Intent intent) 將它啟動。

以 IntentService 作為基類時,其內部其實也重新開了一條線程來干活,只不過這一切都被它妥善封裝,連服務的結束都由它自行管理。換句話說,用它實作的服務會在任務執行完畢後自動收尾,無須人為關閉,特別適合那些「不必費心管理、卻又頗為耗時」的操作。

 

IntentService 範例

以下用一個小實例演示 IntentService:從網路下載一張圖片並存進本機目錄。其中涉及的本機儲存與網路下載圖片,若不熟悉可參考另兩篇:https://www.fengfly.com/plus/view-213506-1.html、https://www.fengfly.com/plus/view-213371-1.html。

IntentSer.java:

 

  1. package cn.bgxt.servicedemohigh; 
  2.  
  3. import java.io.File; 
  4. import java.io.FileOutputStream; 
  5. import java.io.IOException; 
  6. import java.io.InputStream; 
  7. import java.net.MalformedURLException; 
  8. import java.net.URL; 
  9.  
  10. import android.app.IntentService; 
  11. import android.content.Intent; 
  12. import android.util.Log; 
  13. import android.widget.Toast; 
  14.  
  15. public class IntentSer extends IntentService { 
  16.     private final static String TAG = "main"; 
  17.     private String url_path="https://ww2.sinaimg.cn/bmiddle/9dc6852bjw1e8gk397jt9j20c8085dg6.jpg"; 
  18.     public IntentSer() { 
  19.         super("IntentSer"); 
  20.     } 
  21.     @Override 
  22.     public void onCreate() { 
  23.         Log.i(TAG, "Service is Created"); 
  24.         super.onCreate(); 
  25.     } 
  26.      
  27.     @Override 
  28.     public int onStartCommand(Intent intent, int flags, int startId) { 
  29.         Log.i(TAG, "Service is started"); 
  30.         return super.onStartCommand(intent, flags, startId); 
  31.     } 
  32.      
  33.     @Override 
  34.     public void onDestroy() { 
  35.         Log.i(TAG, "Service is Destroyed"); 
  36.         super.onDestroy(); 
  37.     } 
  38.     @Override 
  39.     protected void onHandleIntent(Intent intent) { 
  40.         Log.i(TAG, "HandleIntent is execute"); 
  41.         try { 
  42.             // 在設備應用目錄下創建一個文件 
  43.             File file=new File(this.getFilesDir(), "weibo.jpg"); 
  44.             FileOutputStream fos=new FileOutputStream(file);         
  45.             // 獲取網絡圖片的輸入流 
  46.             InputStream inputStream = new URL(url_path).openStream(); 
  47.             // 把網絡圖片輸入流寫入文件的輸出流中 
  48.             byte[] date=new byte[1024]; 
  49.             int len=-1; 
  50.             while((len=inputStream.read(date))!=-1){ 
  51.                 fos.write(date, 0, len); 
  52.             } 
  53.             
  54.             fos.close(); 
  55.             inputStream.close();    
  56.             Log.i(TAG, "The file download is complete"); 
  57.         } catch (MalformedURLException e) { 
  58.             e.printStackTrace(); 
  59.         } catch (IOException e) { 
  60.             e.printStackTrace(); 
  61.         } 
  62.     } 
  63. }

寫好服務類別後,只需一個 Android 組件即可啟動它。這裡用一個 Activity 來觸發,主要程式碼如下。

  1. btnDownload=(Button)findViewById(R.id.btnDownload); 
  2.         btnDownload.setOnClickListener(new View.OnClickListener() { 
  3.              
  4.             @Override 
  5.             public void onClick(View v) { 
  6.                 // TODO Auto-generated method stub 
  7.                 Intent service=new Intent(MainActivity.this,IntentSer.class); 
  8.                 startService(service); 
  9.             } 
  10.         });

執行結果都寫進了日誌,可透過 LogCat 查看。下載完成後,能在應用安裝目錄下的 /files 看見名為 weibo.jpg 的檔案。

 

Service 生命週期詳解

上一篇雖已談過生命週期,但講得不夠透徹,這裡再補充說明。下圖是官方 API 提供的 Service 生命週期示意:

從圖中可見,啟動服務與綁定服務走的是不同路徑,但大多數被呼叫的方法是一致的,例如 onCreate()、onDestroy() 等;而且無論啟動或綁定同一個服務多少次,這些共用方法也僅被呼叫一次。兩者唯一的差別在於:以 startService() 啟動時回呼的是 onStartCommand(),而以 bindService() 綁定時回呼的是 onBind(),且解除綁定時還會觸發 onUnbind()。

接著分別拆解啟動服務與綁定服務的生命週期:

  • 啟動服務:當某個 Android 組件呼叫 startService() 啟動服務,無論它先前是否曾被 bindService() 綁定過,該服務都會在後台持續運行。由於系統只會為一個 Service 建立單一實例,因此啟動多少次,onCreate() 都只執行一次,但每次啟動都會觸發 onStartCommand()。一旦啟動,就算呼叫方被銷毀,服務仍會運行下去,直到有人呼叫 stopService() 或服務自身的 stopSelf(),當然系統資源吃緊時也可能主動回收。
  • 綁定服務:當某個 Android 組件呼叫 bindService() 綁定服務,同樣因為單一實例的特性,不論被不同組件綁定幾次,onCreate() 都只回呼一次,接著執行 onBind() 完成 Binder 的綁定。連線建立後,服務會持續運行,除非宿主呼叫 unbindService() 斷開,或宿主本身被銷毀。當宿主綁定數量歸零,系統便會自動停止服務並回呼 onDestroy()。

 正如前面所述,系統只為一個 Service 建立單一實例,所以不論啟動或綁定,操作的其實是同一個物件。但若兩種方式同時被呼叫,綁定服務將轉為啟動服務的模式運行——此時就算先前的宿主被銷毀,也不影響服務續航;反過來說,啟動服務並不會因為有宿主 bindService() 就轉為綁定服務,但它仍會與宿主產生綁定關係,只是宿主解除綁定後,服務照舊依啟動服務的生命週期在後台運行,直到有人 stopService() 或服務自身 stopSelf() 才真正銷毀。這樣看來,啟動服務的「續航力」似乎高於綁定服務(系統資源回收的情況不在此討論)。

綜上所述,對於一個同時被 startService() 啟動又被 bindService() 綁定的服務,除非兩條生命週期都走到終點,否則不會被銷毀。也就是說,在不考慮系統主動回收的前提下:以 startService() 啟動者,必須靠 stopService() 或 stopSelf() 才能停止;以 bindService() 綁定者,必須靠 unbindService() 或銷毀宿主才能解除,否則服務將長跑不止。

實務專案裡,經常把兩者混用:既讓關鍵服務在後台長期駐守,又能在需要時透過 bindService() 與它互動,可謂兼得魚與熊掌。

前台服務

無論啟動或綁定,Service 預設都跑在後台。但有一種特殊存在叫「前台服務」,它是使用者能明確感知的服務,因此系統預設不會將它輕易回收。代價是必須提供一個狀態列通知(Notification),在通知欄放置一個持續顯示的標題,除非服務被停止或從前台移除,否則這個通知無法被忽略。關於通知欄的用法,可參考另一篇:Android—通知之 Notification。

 這類服務主要服務於那些「需要使用者意識到它正在後台運行、並隨時可操作」的情境,例如音樂播放器:設為前台服務後,用一個 Notification 常駐通知欄,讓使用者能隨時切歌或暫停。

前台服務的定義規則與一般服務無異,同樣繼承 Service,唯一差別是需在服務中呼叫 Service.startForeground() 將自己標記為前台服務,並指定一則 Notification。以下是 startForeground() 的完整簽名。

public final void startForeground(int id, Notification notification)

其中 id 是唯一標識通知的整數,特別注意這個值不能為 0;notification 則是前台服務對應的通知,只需透過 startForeground() 設定即可,無須像一般通知那樣透過 NotificationManager 操作。

若要讓前台服務退出前台,可呼叫 stopForeground(boolean bool),傳入 false 即可——但這只會讓它離開前台,並不會停止服務。

另外提醒,startForeground() 需 Android 2.0 之後才生效,更早的版本得改用 setForeground() 並搭配 NotificationManager 管理通知。不過如今市面上幾乎已見不到 2.0 以下的裝置,這點無須過度在意。

前台服務—範例

以下示範一個簡單的前台服務:它以通知形式呈現,點擊通知時會開啟一個新的 Activity。

 ForegroundService.java

 

  1. package cn.bgxt.servicedemohigh; 
  2.  
  3. import android.app.Notification; 
  4. import android.app.NotificationManager; 
  5. import android.app.PendingIntent; 
  6. import android.app.Service; 
  7. import android.content.Context; 
  8. import android.content.Intent; 
  9. import android.os.IBinder; 
  10. import android.support.v4.app.NotificationCompat; 
  11.  
  12. public class ForegroundSer extends Service { 
  13.     private Notification notification; 
  14.     @Override 
  15.     public IBinder onBind(Intent intent) { 
  16.         return null; 
  17.     } 
  18.      
  19.     @Override 
  20.     public void onCreate() { 
  21.         super.onCreate(); 
  22.         // 聲明一個通知,並對其進行屬性設置 
  23.         NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(ForegroundSer.this) 
  24.         .setSmallIcon(R.drawable.ic_launcher) 
  25.         .setContentTitle("Foreground Service") 
  26.         .setContentText("Foreground Service Started."); 
  27.         // 聲明一個Intent,用於設置點擊通知後開啟的Activity 
  28.         Intent resuliIntent=new Intent(ForegroundSer.this, IntentSerActivity.class); 
  29.         PendingIntent resultPendingIntent=PendingIntent.getActivity(ForegroundSer.this, 0, resuliIntent, PendingIntent.FLAG_CANCEL_CURRENT); 
  30.         mBuilder.setContentIntent(resultPendingIntent); 
  31.         notification=mBuilder.build(); 
  32.         // 把當前服務設定為前台服務,並指定顯示的通知。 
  33.         startForeground(1,notification); 
  34.     } 
  35.      
  36.     @Override 
  37.     public void onDestroy() {         
  38.         super.onDestroy(); 
  39.         // 在服務銷毀的時候,使當前服務推出前台,並銷毀顯示的通知 
  40.         stopForeground(false); 
  41.     } 
  42. }

控制 Service 的 Activity,與一般啟動服務並無二致。

 

  1. public class ForegroundActivity extends Activity { 
  2.     private Button btnForeStart,btnForeStop; 
  3.     private Intent service; 
  4.     @Override 
  5.     protected void onCreate(Bundle savedInstanceState) { 
  6.         // TODO Auto-generated method stub 
  7.         super.onCreate(savedInstanceState); 
  8.         setContentView(R.layout.layout_foreground); 
  9.         btnForeStart=(Button)findViewById(R.id.btnForeStart); 
  10.         btnForeStop=(Button)findViewById(R.id.btnForeStop); 
  11.         service=new Intent(ForegroundActivity.this, ForegroundSer.class); 
  12.         btnForeStart.setOnClickListener(new View.OnClickListener() {             
  13.             @Override 
  14.             public void onClick(View v) { 
  15.                 // 開始服務 
  16.                 startService(service);                             
  17.             } 
  18.         }); 
  19.         btnForeStop.setOnClickListener(new View.OnClickListener() { 
  20.             @Override 
  21.             public void onClick(View v) { 
  22.                 // 停止服務 
  23.                 stopService(service); 
  24.             } 
  25.         }); 
  26.     } 
  27. }

顯示出來就是一個普通的通知欄,但它代表的其實是一個前台服務:

 

服務資源被系統意外回收

眾所周知,Android 會在系統資源(如 CPU、記憶體)不足時回收資源,強制銷毀一些優先級不高的後台組件。因此使用者啟動的服務很可能在任務尚未完成時就被回收,這時就需要預先規劃「服務被意外銷毀後如何接續」。以 bindService() 綁定的服務與宿主綁定,只要宿主未被回收,服務便不會被輕易銷毀,除非宿主主動解除綁定直到綁定數歸零——這種情況只需關注宿主是否被銷毀即可。而以 startService() 啟動的服務一旦開跑便與宿主無關,除了 stopService() 或 stopSelf(),它很可能在資源吃緊時被回收。對於下載檔案、備份資料這類不允許中斷的重要任務,就必須設定服務被銷毀後的應對策略。

服務被系統銷毀後要如何續命,可透過 Service.onStartCommand() 的回傳值來控制。這個方法必須回傳一個整數,用來告訴系統銷毀後該怎麼辦,這些整數已被系統封裝為常量,常用的有:

  • START_NOT_STICKY:系統銷毀服務後不重建,除非有新的 Intent 再次啟動。
  • START_STICKY:系統銷毀服務後會重建並呼叫 onStartCommand(),但會帶著一個空的 Intent 執行,猶如「只開機、不下指令」,等待後續工作。
  • START_REDELIVER_INTENT:系統銷毀服務後會重建並呼叫 onStartCommand(),並依先前啟動它的 Intent 繼續未完成的任務,例如接續下載檔案。

打造不被銷毀的服務

若希望某個 Service 常駐後台、任何時候都不被銷毀,牽涉的面向較廣,這裡先勾勒思路,需要考慮幾個環節:

  • 開機啟動:Android 開機時會送出 action 為 android.intent.action.BOOT_COMPLETED 的廣播,只要有一個廣播接收者攔截它並在裡頭啟動服務即可。
  • 意外停止:可在服務的 onDestroy() 中重新啟動自己,做到「剛銷毀又重啟」。
  • 意外銷毀:當 Service 被意外銷毀時會發出 action 為 android.intent.action.PACKAGE_RESTARTED 的廣播,監聽它並在其中重啟服務即可。
  • 系統回收:系統回收資源時優先針對低優先級者,因此提高 Service 的優先級有助常駐。可在清單檔的 <service/> 節點下、配置 <intent-filter/> 時加上 android:priority 屬性並設為較高值(數值越高優先級越高,上限為 1000)。

 上述思路大致涵蓋了讓 Service 不被銷毀的主要手法。還有一種極端做法能讓服務一旦啟動便永不銷毀:在清單檔的 <application/> 節點加上 android:persistent 並設為 true。但這是最極端的手段,並不推薦——若系統中安裝了大量常駐組件,反而會拖累整體使用體驗。

源碼下載

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved