編輯:關於 Android 開發
上一篇我們談完了 Activity 與 Intent,這次換 Service 登場。若把 Activity 比喻成使用者看得見的「前台」,那麼 Service 就是默默在幕後運作的「後台」——它沒有使用者介面,整個生命週期都在背景執行,特別適合承接音樂播放、檔案下載、資料同步這類不該被畫面綁住的工作。
這一點和 Activity 完全一致:Service 也是靠 Intent 來呼叫。要在專案裡新增一個 Service,需要兩個步驟。先寫一個繼承 android.app.Service 的類別,把實際要跑的邏輯放進去;接著打開 AndroidManifest.xml,在 Application → Application Nodes 中的 Service 標籤裡把它登記出來。少了第二步,系統根本認不出這個元件。
而從 Activity 這邊要啟動它,有兩個入口:startService() 與 bindService(),參數一樣用 Intent 傳遞。先看一下本文程式的執行結果:

本文的示範重點有兩個:Service 的呼叫方式,以及它在不同情境下的狀態變化。下面這張圖呈現的是 startService() 之後再呼叫 stopService() 時,Service 所經歷的狀態推移:

而這張則是 bindService() 之後再 unbindService() 的狀態變化:

關鍵差異在於「Service 的生命週期由誰掌控」:
stopService() 收尾。若忘了呼叫,就會出現 Activity 已經關閉、Service 卻還在背景跑的情況,白白消耗資源。unbindService() 結束,也可以在 Activity 走到 onDestroy() 時自動解除綁定並隨之結束。下面兩張圖把這個差異說得更清楚。第一張是 startService() 之後直接 Activity.finish() 的狀態變化,可以注意到 Service 依然在跑:

第二張則是 bindService() 之後 Activity.finish() 的狀態變化,Service 最後會自動完成 unbind:

實務上的判斷很簡單:需要長期在背景待命、不依賴任何頁面的工作(例如播放器中斷控制),用 startService;只是需要與某個 Activity 進行雙向溝通、頁面關掉就該收工的工作,用 bindService。
五顆按鈕分別對應啟動、停止、綁定、解綁與退出:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnStartMyService"
android:text="StartMyService">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnStopMyService"
android:text="StopMyService">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnBindMyService"
android:text="BindMyService">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnUnbindMyService"
android:text="UnbindMyService">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/btnExit"
android:text="退出程式">package com.testService;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class testService extends Activity {
Button btnStartMyService, btnStopMyService, btnBindMyService, btnUnbindMyService, btnExit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnStartMyService = (Button) this.findViewById(R.id.btnStartMyService);
btnStartMyService.setOnClickListener(new ClickEvent());
btnStopMyService = (Button) this.findViewById(R.id.btnStopMyService);
btnStopMyService.setOnClickListener(new ClickEvent());
btnBindMyService = (Button) this.findViewById(R.id.btnBindMyService);
btnBindMyService.setOnClickListener(new ClickEvent());
btnUnbindMyService = (Button) this.findViewById(R.id.btnUnbindMyService);
btnUnbindMyService.setOnClickListener(new ClickEvent());
btnExit = (Button) this.findViewById(R.id.btnExit);
btnExit.setOnClickListener(new ClickEvent());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("Activity", "onDestroy");
}
private ServiceConnection _connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
}
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
class ClickEvent implements View.OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent(testService.this, MyService.class);
if (v == btnStartMyService) {
testService.this.startService(intent);
}
else if (v == btnStopMyService) {
testService.this.stopService(intent);
}
else if (v == btnBindMyService) {
testService.this.bindService(intent, _connection, Service.BIND_AUTO_CREATE);
}
else if (v == btnUnbindMyService) {
if (MyService.ServiceState == "onBind") // Service 綁定之後才能解綁
testService.this.unbindService(_connection);
}
else if (v == btnExit) {
testService.this.finish();
}
}
}
}這裡刻意把每個回呼觸發時的狀態寫進一個靜態變數 ServiceState,方便外部按鈕判斷目前是否可以解綁,同時也能搭配 Logcat 觀察整條生命週期:
package com.testService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
static public String ServiceState = "";
@Override
public IBinder onBind(Intent arg0) {
Log.e("Service", "onBind");
ServiceState = "onBind";
return null;
}
@Override
public boolean onUnbind(Intent intent) {
super.onUnbind(intent);
Log.e("Service", "onUnbind");
ServiceState = "onUnbind";
return false;
}
@Override
public void onCreate() {
super.onCreate();
Log.e("Service", "onCreate");
ServiceState = "onCreate";
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e("Service", "onDestroy");
ServiceState = "onDestroy";
}
@Override
public void onStart(Intent intent, int startid) {
super.onStart(intent, startid);
Log.e("Service", "onStart");
ServiceState = "onStart";
}
}把這三段代碼跑起來,反覆點擊按鈕並搭配 Logcat 觀察,你會很直觀地感受到:Service 的「生死」取決於你怎麼啟動它。這也是為什麼在設計背景任務時,第一步永遠是先想清楚——這個服務該由誰來結束。
全面理解 Android 屬性動畫:原理、API 與實戰
Android 屬性動畫完全指南 屬性動畫系統是一個相當強健的框架,它幾乎能把任何物件變成動畫。你可以依據時間的推移去改變任意物件的屬性來定義動畫,而完全不必理會這個物件
Android 模擬 QQ 介面框架:歡迎頁、底部導覽與 Fragment 切換
整體架構這個範例以類似 QQ 的行動應用為靈感,實作歡迎頁、主頁面與底部導覽切換。畫面主要由 WelcomActivity 與 MainActivity 組成,並搭配多個
我的第一個 Android 應用:開發環境與專案結構入門
我的第一個 Android 應用:開發環境與專案結構入門 一、前言 Android(安卓)是一套基於 Linux 的自由及開放原始碼作業系統,主要應用於手機、平板等行動裝
Android 單行向上滾動公告欄控件分享
Android 單行向上滾動公告欄控件分享 在需要展示開獎公告或即時通知的專案中,單行文字向上滾動的公告欄是很實用的元件。它能在有限空間內持續輪播訊息,又不會佔用過多版面