編輯:關於 Android 開發
前面已經大致了解了AsyncTask的多執行緒編程,這次來聊聊Android四大元件之一的Service。要真正精通Service,需要學的東西不少;這一篇的目標是讓新手快速搞懂Service是什麼、怎麼用,屬於入門教程。
順帶一提:如果你還在用Eclipse搭配ADT開發,強烈建議試試Android Studio,理由不必多說,換過來的人多半回不去了。
新增 MyService.java,作為服務類必須繼承 Service(android.app.Service)。其中 onBind() 是抽象方法,子類必須實作:
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) { // 抽象方法,子類必須重寫
return null;
}
}
光這樣還不夠,我們再覆寫幾個常用方法,把服務的骨架補齊:
public void onCreate() { // 服務建立時呼叫
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) { // 服務啟動時呼叫
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() { // 服務銷毀時呼叫
super.onDestroy();
}
這裡要特別強調 onStartCommand()——服務需要處理的邏輯程式碼,通常都寫在這個方法裡。
和Activity一樣,服務也必須在 AndroidManifest.xml 中註冊才會生效,這是四大元件的共同特性:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.xin02ma.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
... >
<activity android:name=".MainActivity">
...
</activity>
<service android:name=".MyService" />
</application>
</manifest>
(1)先在 activity_main.xml 中加入兩個按鈕:
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/start_service" />
<Button
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/stop_service" />

(2)接著修改 MainActivity:
public class MainActivity extends Activity implements View.OnClickListener {
private Button startService;
private Button stopService;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) super.findViewById(R.id.start_service);
stopService = (Button) super.findViewById(R.id.stop_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent); // 啟動服務
break;
case R.id.stop_service:
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent); // 停止服務
break;
default:
break;
}
}
}
程式碼很簡單,主要做了兩件事:取得兩個按鈕的實例並註冊點擊事件;透過Intent物件呼叫 startService() 與 stopService() 來啟動與停止服務。
不過這裡有個問題:服務的啟動與停止完全由Activity掌控,如果啟動後一直沒按 stop,服務就會持續運行。那服務能不能自己停下來?可以——呼叫 stopSelf() 即可,不需要Activity介入。
口說無憑,我們加上Log,實際觀察服務的建立、啟動與銷毀時機:
private static final String TAG = "MyService";
public void onCreate() { // 服務建立時呼叫
super.onCreate();
Log.d(TAG, "onCreate executed");
}
public int onStartCommand(Intent intent, int flags, int startId) { // 服務啟動時呼叫
Log.d(TAG, "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() { // 服務銷毀時呼叫
super.onDestroy();
Log.d(TAG, "onDestroy executed");
}
只加了3行Log,卻能清楚看出服務的何時建立、何時啟動、何時銷毀。別小看這個步驟,理解Service生命週期對日後寫程式非常重要。
執行結果如下:

(1)第一次點擊 StartService 後,onCreate() 與 onStartCommand() 都被執行(圖中黃色箭頭)。此時在手機的「設定 → 應用 → 執行中」裡也能看到這個服務正在運行。


(2)接著點擊 stopService,onDestroy() 被執行(圖中藍色箭頭)。
(3)這時可能會有疑問:同時執行的 onCreate() 與 onStartCommand() 差在哪?圖中的紅色箭頭給出了答案——onCreate() 只在服務第一次建立時呼叫,而 onStartCommand() 每次啟動服務都會被呼叫。
也就是說:服務未啟動時按 startService,兩個方法都會執行;服務啟動完成後,再按多少次 startService,都只會執行 onStartCommand()。
Android 應用集成 Google 登陸(Google Sign-In)完整流程
Google Sign-In 是接入第三方賬號登陸最常見的方案之一。整個集成過程可以拆成兩部分:先在 Google Cloud 平台完成應用註冊與配置,再在項目裡添加依賴
Android Activity 啟動模式:singleTop 行為與範例
Android Activity 啟動模式:singleTop 行為與範例singleTop 模式的特色是:如果目標 Activity 已經位於任務棧頂端,再次啟動它時不
Android 動態連結庫加載原理與 HotFix 思路
動態連結庫加載流程 Android 中常見的動態連結庫是 so 檔。當我們呼叫 System.loadLibrary 時,系統會先尋找 so 檔所在位置,再將它載入記憶體
深入理解 Android 沉浸式狀態欄的實現原理
對沉浸式狀態欄的理解 Android 4.4 版本加入了「沉浸式」這項功能,如今大家手中的安卓手機早已是 4.4 甚至更高版本,越來越多的應用實現了沉浸式狀態欄效果。 先