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

Android Service 詳解:概念、生命週期與兩種啟動方式的實際對照

編輯:關於 Android 程式設計

Service 是什麼

(1)可以粗略地把 Service 想成「一個沒有畫面的 Activity」。它不是獨立進程(除非另外指定),預設與 App 跑在同一個進程的主線程上。你只要告訴它要在後台做什麼,它就去做。

(2)Service 本身沒有 UI,若要與使用者互動,得透過通知欄或發送廣播,由 Activity 接收後呈現。

(3)它的用處非常廣泛,尤其在框架層——系統服務的呼叫大多經由 Service 完成。

它解決什麼問題

(1)處理那些不該干擾使用者操作、又不適合丟在 Activity 裡的後台工作,例如檔案下載、網路同步、音樂播放。它可以被 Intent 啟動,也可以綁定到宿主對象(如 Activity)上使用。

(2)如果 Activity 負責呈現前台資訊,Service 就是在後台幹活的那一位;兩者要溝通,走廣播或通知欄。

生命週期

(1)Service 的整體存活時間從 onCreate() 被呼叫開始,到 onDestroy() 回傳結束。與 Activity 一樣,初始化寫在 onCreate(),資源釋放寫在 onDestroy()。

(2)startService() 路徑:onCreate() → onStartCommand() → onStart() → onDestroy()

(3)bindService() 路徑:onCreate() → onBind() → onUnbind() → onDestroy(),onUnbind() 回傳後服務即結束。

啟動方式

(1)Service 無法自行啟動,必須由某個 Activity 或其他 Context 物件來調用。

(2)兩種啟動 API:Context.startService() 與 Context.bindService()。若 onCreate() 或 onStartCommand() 裡有耗時操作,必須另開線程。

注意:實務上最常用的是 startService,把耗時任務丟到後台,完成後再用廣播或通知欄告知前台。

程式碼示範

MainActivity:兩個按鈕分別示範兩種啟動方式。

public class MainActivity extends Activity implements OnClickListener {
    private static String TAG = "com.example.servicetest.MainActivity";
    private Button mBtnStart;
    private Button mBtnBind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mBtnStart = (Button) findViewById(R.id.startservice);
        mBtnBind = (Button) findViewById(R.id.bindservice);
        mBtnStart.setOnClickListener(this);
        mBtnBind.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.startservice:
                startService(new Intent(MyService.ACTION));
                break;
            case R.id.bindservice:
                bindService(new Intent(MyService.ACTION), conn, BIND_AUTO_CREATE);
                break;
            default:
                break;
        }
    }

    ServiceConnection conn = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.v(TAG, "onServiceConnected");
        }
        public void onServiceDisconnected(ComponentName name) {
            Log.v(TAG, "onServiceDisconnected");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(MyService.ACTION));
        unbindService(conn);
    }
}

MyService:把每個回呼都印出來,方便觀察順序。

public class MyService extends Service {
    private static String TAG = "com.example.servicetest.service.MyService";
    public static final String ACTION = "com.example.servicetest.service.MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("----- onCreate() ---");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        System.out.println("----- onStart() ---");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("----- onStartCommand() ---");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent arg0) {
        System.out.println("----- onBind() ---");
        return null;
    }

    @Override
    public void onRebind(Intent intent) {
        System.out.println("----- onRebind() ---");
        super.onRebind(intent);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        System.out.println("----- onUnbind() ---");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        System.out.println("----- onDestroy() ---");
        super.onDestroy();
    }
}

AndroidManifest.xml:別忘了註冊。

<service android:name="com.example.servicetest.service.MyService">
    <intent-filter>
        <action android:name="com.example.servicetest.service.MyService" />
        <category android:name="android.intent.category.default" />
    </intent-filter>
</service>

實際操作對照

startService 路徑

第一次按下 startService:

再按一次 startService:

可以清楚看到 onCreate 只出現一次,onStartCommand(以及舊版 onStart)則每次都有。這印證了 Service 的實例只會被創建一次,後續啟動只是重複投遞請求。

bindService 路徑

第一次按下 bindService:

再按一次 bindService:

先按 startService 再按 bindService:

這張圖最值得注意:兩種方式混用時,Service 不會因為其中一方解除關係就結束,必須等 stopService 與所有 unbindService 都發生,才會走到 onDestroy。

補充:幾個實務上一定要知道的事

  • onStartCommand 的回傳值決定被殺後的行為:START_STICKY 會重建服務但 Intent 為 null;START_NOT_STICKY 不重建;START_REDELIVER_INTENT 會重建並重投最後一個未完成的 Intent。
  • Service 默認跑在主線程,網路、檔案、運算一律要自己開線程,或用 IntentService / JobIntentService 現成方案。
  • Android 8.0 起有背景執行限制,App 進入背景後 startService 會拋 IllegalStateException,長時間任務請改用 startForegroundService 並在 5 秒內呼叫 startForeground 顯示通知。
  • bindService 的 Binder 可以為 null,此時只是「綁定但不通訊」,常用於讓 Service 隨宿主存活。
  • onUnbind() 回傳 true 時,後續再有客戶端綁定會走到 onRebind(),這也是範例中刻意印出來的原因。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved