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

Android 進階第五篇:Service 的兩種啟動方式與生命週期

編輯:Android 開發實例

上一篇講了 Activity 與 Intent,這次換 Service。如果把 Activity 當成前台程式,那 Service 就是沒有介面的後台程式,整個生命週期都在背後執行。它和 Activity 一樣由 Intent 驅動,參數也靠 Intent 傳遞。

要在專案裡新增一個 Service,兩步:先寫一個繼承 Service 的類別,再到 AndroidManifest.xml → Application → 新增 <service> 標籤把它登記進去。少了第二步,startService() 會直接丟出 ActivityNotFoundException。

startService 與 bindService 差在哪

兩者都能啟動 Service,真正的差別是生命週期的歸屬:

  • startService:Service 一旦啟動就獨立存活,必須由 stopService() 明確結束。若只在 Activity 裡 start 卻沒 stop,會出現「畫面關掉了、Service 還在跑」的情況,白白耗電。
  • bindService:Service 與呼叫者綁在一起,可以用 unbindService() 解開;即使不解,當 Activity 走到 onDestroy() 時,系統也會自動幫你解綁並回收。

一句話記法:需要「按鈕按下去後持續在背景做事」,用 startService;需要「Activity 與 Service 之間雙向溝通、跟著畫面存亡」,用 bindService。

MyService.java:把每個回呼都印出來

觀察生命週期最直接的方式,就是在每個回呼裡打 log。這支 Service 另外用一個靜態變數 ServiceState 記住目前狀態,方便 Activity 查詢(例如解綁前先確認是否處於 onBind)。

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 void onCreate() {
        super.onCreate();
        Log.e("Service", "onCreate");
        ServiceState = "onCreate";
    }

    @Override
    public void onStart(Intent intent, int startid) {
        super.onStart(intent, startid);
        Log.e("Service", "onStart");
        ServiceState = "onStart";
    }

    @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 onDestroy() {
        super.onDestroy();
        Log.e("Service", "onDestroy");
        ServiceState = "onDestroy";
    }
}

觀察 log 的順序,可以歸納出兩條不同的路徑:startService 走的是 onCreate → onStart →(stopService)→ onDestroy;bindService 走的是 onCreate → onBind →(unbindService)→ onUnbind → onDestroy。

testService.java:Activity 端

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) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    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") {   // 綁定之後才能解綁
                    testService.this.unbindService(_connection);
                }
            } else if (v == btnExit) {
                testService.this.finish();
            }
        }
    }
}

要留意 bindService 的第三個參數 BIND_AUTO_CREATE:它表示目標 Service 不存在時順手把它建起來。如果傳 0,Service 只會在已經活著時才綁得上。另外 ServiceConnection 的兩個回呼裡通常會拿到 IBinder——那才是呼叫 Service 公開方法的入口;範例中 Service 的 onBind() 回傳 null,所以只示範了生命週期,沒有跨元件呼叫。

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button android:id="@+id/btnStartMyService"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="StartMyService" />

    <Button android:id="@+id/btnStopMyService"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="StopMyService" />

    <Button android:id="@+id/btnBindMyService"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="BindMyService" />

    <Button android:id="@+id/btnUnbindMyService"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="UnbindMyService" />

    <Button android:id="@+id/btnExit"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="退出程序" />
</LinearLayout>

把 Activity 關掉之後會發生什麼

這是本篇最值得記住的實驗:startService 之後呼叫 Activity.finish(),Service 完全不為所動,繼續在背景跑到你 stop 它為止;而 bindService 之後 finish,Service 會在 onDestroy 時被動地走完 onUnbind → onDestroy。理解這一點,就不會寫出「使用者退出 App 後音樂還在無限播放」這種 bug。

現代 Android 的補充

值得說明的是,這套 API 在後續版本有幾個重要變化:onStart() 已被 onStartCommand() 取代;從 Android 8.0 起,背景執行有嚴格的分段限制,長時間的常駐工作應該改用 Foreground Service(必須顯示常駐通知)或 WorkManager;而 bindService 這種模式至今仍然是 Activity 與 Service 雙向通訊的正統做法,搭配 LocalBinder 取得 Service 實例即可直接呼叫其方法。

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