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

Android Service 完全指南:startService 與 bindService 的生命周期差異與通信實踐

編輯:關於 Android 程式設計

Service 是 Android 四大組件之一,它沒有界面,卻承擔著在後台持續工作的責任。它由 Activity 或其他 Context 啟動,可以在用戶離開應用之後繼續運行——比如音樂播放、文件下載、定位上報。

兩種啟動方式,兩套生命周期

方式一:直接啟動(startService)

Intent intent = new Intent(ActivityA.this, ServiceA.class);
startService(intent);

回調順序是 onCreate → onStartCommand → onDestroy。

這裡有個必須警惕的陷阱:如果只調用 startService 而沒有在合適的時機調用 stopService 或 stopSelf,Service 會一直駐留在後台運行,用戶退出應用也停不下來。這不僅浪費電量和內存,也容易招致系統或用戶的「殺進程」行為。

方式二:綁定(bindService)

如果 Service 尚未啟動,回調順序是 onCreate → onDestroy(注意這裡走的是 onBind 而非 onStartCommand)。如果 Service 已經啟動,Activity 綁定時不會再次觸發 onCreate。無論哪種情況,Activity 退出前必須調用 unbindService 解綁,否則會拋出洩漏異常。

Service 的實現

下面這個 Service 通過內部 Binder 類把自身實例暴露給綁定方,从而实现「Activity 直接調用 Service 方法」的能力:

public class ServiceA extends Service {

    @Override
    public void onCreate() {
        Toast.makeText(this, "Service onCreate", Toast.LENGTH_SHORT).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new LocalBinder();
    }

    /** 內部 Binder:把 Service 實例交給綁定方 */
    public class LocalBinder extends Binder {
        public ServiceA getService() {
            return ServiceA.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Received start id " + startId + ": " + intent,
                Toast.LENGTH_SHORT).show();
        // START_STICKY:Service 被系統回收後會嘗試重建
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service onDestory", Toast.LENGTH_SHORT).show();
    }

    /** 供外部調用的業務方法 */
    public void doSomething() {
        Toast.makeText(this, "Service do something", Toast.LENGTH_SHORT).show();
    }
}

onStartCommand() 的返回值值得單獨說一下:START_STICKY 表示進程被殺後系統會重建 Service 但 Intent 為空;START_NOT_STICKY 表示不重建;START_REDELIVER_INTENT 則會重建並重新投遞最後一個 Intent,適合下載這類不能丟任務的場景。

Activity 側:綁定、通信與解綁

package com.example.servicetest;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button bindServiceBtn;
    private Button unbindServiceBtn;
    private boolean mIsBound = false;
    private ServiceA mBoundService;

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

    private void initViews() {
        bindServiceBtn = (Button) findViewById(R.id.button_bindservice);
        bindServiceBtn.setOnClickListener(this);

        unbindServiceBtn = (Button) findViewById(R.id.button_unbindservice);
        unbindServiceBtn.setOnClickListener(this);
        unbindServiceBtn.setEnabled(false);   // 未綁定時禁用解綁按鈕
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_bindservice:
                doBindService();
                break;
            case R.id.button_unbindservice:
                doUnbindService();
                break;
        }
    }

    /** ServiceConnection 是綁定狀態的觀察者 */
    private ServiceConnection mConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className, IBinder service) {
            Toast.makeText(MainActivity.this, "This service connected",
                    Toast.LENGTH_SHORT).show();
            // 連接建立後,把 IBinder 轉成具體類型即可直接調用 Service 方法
            // 因為是我們自己進程內顯式綁定的 Service,轉型是安全的
            mBoundService = ((ServiceA.LocalBinder) service).getService();
            if (mBoundService != null) {
                mBoundService.doSomething();
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            // 進程崩潰等意外斷連時回調;同進程內一般不會出現
            mBoundService = null;
            Toast.makeText(MainActivity.this,
                    "This service disconnected unexpectedly",
                    Toast.LENGTH_SHORT).show();
            unbindServiceBtn.setEnabled(false);
        }
    };

    void doBindService() {
        Toast.makeText(MainActivity.this, "Begin to bind a service.",
                Toast.LENGTH_SHORT).show();
        // BIND_AUTO_CREATE:Service 不存在時自動創建
        bindService(new Intent(MainActivity.this, ServiceA.class),
                    mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
        unbindServiceBtn.setEnabled(true);
    }

    void doUnbindService() {
        if (mIsBound) {
            Toast.makeText(MainActivity.this, "Begin to unbind a service.",
                    Toast.LENGTH_SHORT).show();
            unbindService(mConnection);
            mIsBound = false;
            unbindServiceBtn.setEnabled(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 兜底:Activity 銷燬時順手停掉 Service
        stopService(new Intent(MainActivity.this, ServiceA.class));
    }
}

實戰中的幾點判斷

只顧跑任務、不需要交互,用 startService,並且在任務結束時調用 stopSelf 主動收工。

需要頻繁雙向調用,用 bindService,通過 LocalBinder 拿到 Service 實例直接調方法,比通過 Intent 傳遞消息自然得多。

兩者兼備也很常見:先 startService 保證 Service 不被輕易回收,再 bindService 建立通信通道,並在退出時同時 stopService 與 unbindService。

別忘了主線程問題。Service 默認運行在應用的主線程裡,它並不等於「子線程」。耗時操作必須自己開線程,或者使用 IntentService(已在新版本中被 WorkManager 取代)來避免 ANR。

從 Android 8.0 開始,後台啟動限制收緊,直接 startService 在應用退到後台時會拋出 IllegalStateException,此時應改用 startForegroundService() 並在 5 秒內調用 startForeground() 顯示通知。長時間任務更推薦交給 WorkManager 或前台 Service 來承載。

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