Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android實用技術(3)——Service入門:定義、註冊與生命週期(Ⅰ)

編輯:關於 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驗證生命週期

口說無憑,我們加上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()。

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