編輯:Android 開發實例
前言
上一篇我們談過 Service 的基礎操作,若還不熟悉這塊,建議先回頭複習。本文則要往更深處走,盤點 Service 在實務開發中必須留意的細節與進階玩法,並搭配範例逐一示範,最後同樣附上源碼下載。
本文涵蓋以下重點:
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:
- package cn.bgxt.servicedemohigh;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.MalformedURLException;
- import java.net.URL;
- import android.app.IntentService;
- import android.content.Intent;
- import android.util.Log;
- import android.widget.Toast;
- public class IntentSer extends IntentService {
- private final static String TAG = "main";
- private String url_path="https://ww2.sinaimg.cn/bmiddle/9dc6852bjw1e8gk397jt9j20c8085dg6.jpg";
- public IntentSer() {
- super("IntentSer");
- }
- @Override
- public void onCreate() {
- Log.i(TAG, "Service is Created");
- super.onCreate();
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Log.i(TAG, "Service is started");
- return super.onStartCommand(intent, flags, startId);
- }
- @Override
- public void onDestroy() {
- Log.i(TAG, "Service is Destroyed");
- super.onDestroy();
- }
- @Override
- protected void onHandleIntent(Intent intent) {
- Log.i(TAG, "HandleIntent is execute");
- try {
- // 在設備應用目錄下創建一個文件
- File file=new File(this.getFilesDir(), "weibo.jpg");
- FileOutputStream fos=new FileOutputStream(file);
- // 獲取網絡圖片的輸入流
- InputStream inputStream = new URL(url_path).openStream();
- // 把網絡圖片輸入流寫入文件的輸出流中
- byte[] date=new byte[1024];
- int len=-1;
- while((len=inputStream.read(date))!=-1){
- fos.write(date, 0, len);
- }
- fos.close();
- inputStream.close();
- Log.i(TAG, "The file download is complete");
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
寫好服務類別後,只需一個 Android 組件即可啟動它。這裡用一個 Activity 來觸發,主要程式碼如下。
- btnDownload=(Button)findViewById(R.id.btnDownload);
- btnDownload.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // TODO Auto-generated method stub
- Intent service=new Intent(MainActivity.this,IntentSer.class);
- startService(service);
- }
- });
執行結果都寫進了日誌,可透過 LogCat 查看。下載完成後,能在應用安裝目錄下的 /files 看見名為 weibo.jpg 的檔案。
Service 生命週期詳解
上一篇雖已談過生命週期,但講得不夠透徹,這裡再補充說明。下圖是官方 API 提供的 Service 生命週期示意:
從圖中可見,啟動服務與綁定服務走的是不同路徑,但大多數被呼叫的方法是一致的,例如 onCreate()、onDestroy() 等;而且無論啟動或綁定同一個服務多少次,這些共用方法也僅被呼叫一次。兩者唯一的差別在於:以 startService() 啟動時回呼的是 onStartCommand(),而以 bindService() 綁定時回呼的是 onBind(),且解除綁定時還會觸發 onUnbind()。
接著分別拆解啟動服務與綁定服務的生命週期:
正如前面所述,系統只為一個 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
- package cn.bgxt.servicedemohigh;
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.PendingIntent;
- import android.app.Service;
- import android.content.Context;
- import android.content.Intent;
- import android.os.IBinder;
- import android.support.v4.app.NotificationCompat;
- public class ForegroundSer extends Service {
- private Notification notification;
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public void onCreate() {
- super.onCreate();
- // 聲明一個通知,並對其進行屬性設置
- NotificationCompat.Builder mBuilder=new NotificationCompat.Builder(ForegroundSer.this)
- .setSmallIcon(R.drawable.ic_launcher)
- .setContentTitle("Foreground Service")
- .setContentText("Foreground Service Started.");
- // 聲明一個Intent,用於設置點擊通知後開啟的Activity
- Intent resuliIntent=new Intent(ForegroundSer.this, IntentSerActivity.class);
- PendingIntent resultPendingIntent=PendingIntent.getActivity(ForegroundSer.this, 0, resuliIntent, PendingIntent.FLAG_CANCEL_CURRENT);
- mBuilder.setContentIntent(resultPendingIntent);
- notification=mBuilder.build();
- // 把當前服務設定為前台服務,並指定顯示的通知。
- startForeground(1,notification);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- // 在服務銷毀的時候,使當前服務推出前台,並銷毀顯示的通知
- stopForeground(false);
- }
- }
控制 Service 的 Activity,與一般啟動服務並無二致。
- public class ForegroundActivity extends Activity {
- private Button btnForeStart,btnForeStop;
- private Intent service;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setContentView(R.layout.layout_foreground);
- btnForeStart=(Button)findViewById(R.id.btnForeStart);
- btnForeStop=(Button)findViewById(R.id.btnForeStop);
- service=new Intent(ForegroundActivity.this, ForegroundSer.class);
- btnForeStart.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 開始服務
- startService(service);
- }
- });
- btnForeStop.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // 停止服務
- stopService(service);
- }
- });
- }
- }
顯示出來就是一個普通的通知欄,但它代表的其實是一個前台服務:
服務資源被系統意外回收
眾所周知,Android 會在系統資源(如 CPU、記憶體)不足時回收資源,強制銷毀一些優先級不高的後台組件。因此使用者啟動的服務很可能在任務尚未完成時就被回收,這時就需要預先規劃「服務被意外銷毀後如何接續」。以 bindService() 綁定的服務與宿主綁定,只要宿主未被回收,服務便不會被輕易銷毀,除非宿主主動解除綁定直到綁定數歸零——這種情況只需關注宿主是否被銷毀即可。而以 startService() 啟動的服務一旦開跑便與宿主無關,除了 stopService() 或 stopSelf(),它很可能在資源吃緊時被回收。對於下載檔案、備份資料這類不允許中斷的重要任務,就必須設定服務被銷毀後的應對策略。
服務被系統銷毀後要如何續命,可透過 Service.onStartCommand() 的回傳值來控制。這個方法必須回傳一個整數,用來告訴系統銷毀後該怎麼辦,這些整數已被系統封裝為常量,常用的有:
打造不被銷毀的服務
若希望某個 Service 常駐後台、任何時候都不被銷毀,牽涉的面向較廣,這裡先勾勒思路,需要考慮幾個環節:
上述思路大致涵蓋了讓 Service 不被銷毀的主要手法。還有一種極端做法能讓服務一旦啟動便永不銷毀:在清單檔的 <application/> 節點加上 android:persistent 並設為 true。但這是最極端的手段,並不推薦——若系統中安裝了大量常駐組件,反而會拖累整體使用體驗。
源碼下載
Android JSON 解析入門:從天氣資料擷取所需欄位
JSON 是一種以文字為基礎的資料交換格式,因結構簡單、可讀性高,常用於 Android 應用與網路服務之間傳輸資料。相較於 XML,JSON 的標記較少,解析也較直接,
Android JSON 剖析教學:JSONObject 與天氣資料
在 Android 開發中,JSON 解析是取得遠端資料的關鍵步驟。相較於 XML,JSON 更精簡,也更容易與 Web API 搭配。 先找出需要的欄位 解析前,先確認
Android MediaPlayer 深度說明:音訊播放控制與播放器範例
Android 提供多種播放音訊與影片的方式,而其中最廣為使用的莫過於 MediaPlayer 類別。它代表系統內建媒體播放服務的用戶端介面,能處理本機檔案、網路串流,音
Android 輕鬆實作淘寶風格地區選擇
淘寶在編輯地址時的地區選擇,最大特色是列表滾動時,新項目會從下方滑入並貼近上一項。本文以自製 Demo 重現這種效果,適合想替表單加入更細膩動畫的 Android 開發者