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

Android Service 全面總結:Started、Bound、IntentService 與前台 Service

編輯:關於 Android 程式設計

Service 常被稱為「後台服務」,這裡的「後台」是相對於前台可視界面而言——它自身的運行不依賴用戶可見的 UI。從業務角度看,適合使用 Service 的場景通常具備兩個特徵:一是需要長期運行,二是不依賴用戶可視界面(前台 Service 是個例外,它需要與通知欄配合)。

一、在 AndroidManifest.xml 中聲明

從啟動方式看,Service 分為 Started Service 與 Bound Service。無論哪種,都通過繼承 Service 基類自定義,並且必須在清單中聲明:

<service
    android:enabled="true"
    android:exported="false"
    android:icon="drawable resource"
    android:isolatedProcess="false"
    android:label="string resource"
    android:name="string"
    android:permission="string"
    android:process="string" >
    . . .
</service>

其中 android:name 對應類名,android:permission 是訪問權限,android:process 指定運行進程。Service 能否獨立於一個進程,與其啟動方式有關。

易錯點:自定義 Service 若忘記聲明,不會像 Activity 那樣直接崩潰。顯式 Intent 啟動時只會打印一條 warning:IllegalArgumentException: Service not registered,不容易察覺,排查問題時容易繞彎路。

二、Started Service

通過 context.startService(intent) 啟動,context.stopService(intent) 停止;Service 內部也可以調用 stopSelf(...) 自行停止。

1. 自定義

public class MyService extends Service {

    public static final String TAG = "MyService";

    @Override
    public IBinder onBind(Intent intent) {
        return null;      // Started Service 直接返回 null
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.w(TAG, "in onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.w(TAG, "in onStartCommand");
        String name = intent.getStringExtra("name");
        Log.w(TAG, "name: " + name);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.w(TAG, "in onDestroy");
    }
}

onBind() 是 Service 基類唯一的抽象方法,子類必須實現;但對 Started Service 而言,直接返回 null 即可。onCreate、onStartCommand、onDestroy 分別對應生命週期的三個階段。

2. 生命週期規律

onCreate (首次 startService)
  → onStartCommand
    → onStartCommand (可多次)
      → onDestroy (stopService)
  • 首次調用 startService 時依次執行 onCreate 與 onStartCommand;之後每次調用只執行 onStartCommand,因為 Service 已創建。
  • 無論調用多少次 startService,只需一次 stopService 即可終止(onDestroy 與 onCreate 相互對應)。
  • 同一類型的 Service 實例永遠只有一個,無論發起方是不是同一個組件、是否處於同一進程。
  • Service 的生命週期與客戶端組件的生命週期無關,只有 stopService / stopSelf 才能停止它(系統內存不足或用戶強制停止除外)。
  • A 啟動的 Service,B 或 C 都可以調用 stopService 結束它。
  • 對未啟動的 Service 調用 stopService 不會報錯,無需事先判斷。
  • 用戶強制 kill 進程時,onDestroy 不會被執行。

3. onStartCommand 的返回值

參數 flags 默認為 0(START_STICKY_COMPATIBILITY),startId 是本次請求的唯一標識,多次啟動時遞增。返回值決定 Service 被系統回收後的行為:

  • START_NOT_STICKY:被系統因內存不足殺死後,即使之後內存充足也不會重建。除非客戶端明確再次 startService。
  • START_STICKY:被殺死後,系統在內存充足時會嘗試重建,重建後回調 onStartCommand,但 Intent 為 null(PendingIntent 情況除外)。
  • START_REDELIVER_INTENT:與上者類似,但回調時 Intent 非空,是最後一次 startService 傳入的 intent。
  • START_STICKY_COMPATIBILITY:START_STICKY 的兼容版本,不保證被殺後一定會再次回調 onStartCommand,一般不使用。

極易誤解的一點:以上行為僅在「系統因內存不足而回收」時生效。如果是用戶主動 kill 進程,那麼無論返回值設為什麼,Service 都不會重啟。

廠商定制差異:部分定制系統(如 MIUI)有「自啟動管理」列表,默認只允許少數應用自啟動。用戶手動加入白名單後,若 onStartCommand 返回 START_STICKY 或 START_REDELIVER_INTENT,結束 App 後 Service 仍可按上述規則重啟;但在「設置 → 應用 → 強制停止」中結束的,不會重啟。

4. 進程與通信

需要獨立進程時,在清單中通過 android:process 指定進程名,並在需要對外開放時把 android:exported 設為 true(有 intent-filter 時默認即為 true):

<service
    android:name=".MyService"
    android:exported="true"
    android:process=":MyCorn" />

參數傳遞:啟動時可通過 Intent 直接帶參數;Service 執行中若需回傳數據給客戶端,通常借助發送廣播(客戶端需註冊廣播接收器)。同進程時推薦顯式 Intent,跨應用時只能使用隱式 Intent。

三、Bound Service

Bound Service 的核心特徵是:生命週期依附於客戶端。所有客戶端都解綁後,Service 銷毀。它通過 Binder 對象提供便捷的雙向通信能力。

使用步驟

  1. 自定義 Service 繼承基類,重寫 onBind() 返回具體的 Binder 對象。
  2. 客戶端實現 ServiceConnection 接口,調用 bindService(intent, sc, flags) 綁定。
  3. 在 onServiceConnected(name, binder) 中拿到 Binder 實例。
  4. 通過 Binder 調用 Service 的公共方法完成通信。
  5. 在合適的生命週期(如 onDestroy)調用 unbindService(sc) 解綁。

方式一:繼承 Binder 類

最常見也最簡單的一種。

局限:客戶端與 Service 必須處於同一進程,無法跨進程通信,否則會出現 android.os.BinderProxy cannot be cast to xxx 錯誤。

public class MyBindService extends Service {

    private MyBinder mBinder = new MyBinder();

    public class MyBinder extends Binder {
        MyBindService getService() {
            return MyBindService.this;
        }
    }

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

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
}
public class BActivity extends Activity {

    private ServiceConnection sc = new MyServiceConnection();
    private MyBinder mBinder;
    private MyBindService mBindService;
    private boolean mBound;

    private class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            mBinder = (MyBinder) binder;
            mBindService = mBinder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;   // 進程意外崩潰時調用
        }
    }

    private void bind() {
        bindService(new Intent(this, MyBindService.class),
                sc, Context.BIND_AUTO_CREATE);
    }

    private void unbind() {
        if (mBound) {
            unbindService(sc);
            mBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbind();
    }
}

首次綁定的回調順序:onCreate → onBind → onServiceConnected。再次綁定不會有任何回調。解綁時:onUnbind → onDestroy。

注意:BroadcastReceiver 不能作為 Bound Service 的客戶端,因為它的生命週期太短,onReceive 執行完即結束。有此需求時應改用 startService。

方式二:使用 Messenger

Messenger 可以理解為「信使」。通過它返回 Binder,不必關心客戶端與 Service 是否同進程,並且能實現雙向通信。

局限:不支持嚴格意義的多線程並發,實際以隊列串行處理。

public class MyMessengerService extends Service {

    public static final int MSG_FROM_CLIENT_TO_SERVER = 1;
    public static final int MSG_FROM_SERVER_TO_CLIENT = 2;

    private Messenger mClientMessenger;
    private Messenger mServerMessenger = new Messenger(new ServerHandler());

    @Override
    public IBinder onBind(Intent intent) {
        return mServerMessenger.getBinder();
    }

    class ServerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FROM_CLIENT_TO_SERVER:
                    mClientMessenger = msg.replyTo;   // 取出客戶端信使
                    Message toClient = Message.obtain(
                            null, MSG_FROM_SERVER_TO_CLIENT);
                    try {
                        mClientMessenger.send(toClient);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }
}
public class CActivity extends Activity {

    private ServiceConnection sc = new MyServiceConnection();
    private boolean mBound;
    private Messenger mServerMessenger;

    private Messenger mClientMessenger =
            new Messenger(new MyClientHandler());

    private class MyClientHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MyMessengerService.MSG_FROM_SERVER_TO_CLIENT) {
                Log.w(TAG, "receive msg from server");
            }
        }
    }

    private class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            mServerMessenger = new Messenger(binder);
            mBound = true;
        }

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

    public void sayHello() {
        if (!mBound) return;
        Message msg = Message.obtain(null,
                MyMessengerService.MSG_FROM_CLIENT_TO_SERVER, 0, 0);
        msg.replyTo = mClientMessenger;      // 把自己的信使帶過去
        try {
            mServerMessenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

關鍵環節:Service 端通過 new Messenger(new ServerHandler()) 創建信使並在 onBind 中返回其 Binder;客戶端在 onServiceConnected 中用 new Messenger(binder) 還原;發消息時通過 msg.replyTo 把自己的信使傳過去,Service 便能反向推送。雙向通信由此建立。

方式三:AIDL

Messenger 通常足以勝任,AIDL 則更加靈活——真正的並發調用、支持多種數據類型。做法是自定義 .aidl 文件,構建系統會在 gen 目錄生成接口類,後續流程與 Messenger 類似。

通用注意:無論哪種 Bound Service,執行 unbind 前都必須判斷當前是否處於已綁定狀態,重複解綁會導致崩潰。這與 Started Service 形成鮮明對比——stopService 無需判斷。

四、Local Service 與 Remote Service

  • Local Service:又稱本地服務,客戶端與 Service 處於同一進程。
  • Remote Service:又稱遠程服務,Service 運行於獨立進程,需通過 AIDL 或 Messenger 通信。

五、Service 的兩個關鍵特性

  1. Service 默認運行在主線程。若與客戶端同進程,就是 UI 線程。因此「長期操作」必須自行開子線程,否則會阻塞 UI 甚至觸發 ANR。這是最常見的誤區——Service 本身並不等於後台線程。
  2. Service 不會自己停止。Started Service 必須顯式調用 stopService / stopSelf,Bound Service 必須 unbindService,否則會一直運行消耗資源。

六、IntentService

IntentService 是系統提供的特殊 Service 子類,它解決了「Service 中要開線程」的痛點:

  1. 已實現 onBind() 返回 null,並定義抽象方法 onHandleIntent() 供子類實現。
  2. onHandleIntent() 運行在系統自動創建的工作線程中,無需自己開線程。
  3. 任務執行完畢後自動結束,無需手動調用停止方法。
  4. 多個任務按隊列順序依次處理,並非真正的多線程並發。
public class MyIntentService extends IntentService {

    public static final String TAG = "MyIntentService";

    public MyIntentService() {
        super(TAG);
    }

    public MyIntentService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.w(TAG, "in onHandleIntent");
        Log.w(TAG, "thread name: " + Thread.currentThread().getName());
    }
}

(順序處理的特性決定了它適合離線上報、下載隊列這類串行任務;並發場景應改用 JobIntentService 或 WorkManager。)

七、前台 Service

通過 startForeground(int id, Notification notification) 可以把 Service 提升為前台 Service。在 UI 上它表現為一條持續狀態的通知,同時讓 Service 擁有更高的進程優先級,降低被系統回收的概率。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Notification notification = new Notification(
            R.drawable.ic_launcher, "test", System.currentTimeMillis());

    Intent notificationIntent = new Intent(this, DActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(
            this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, "title", "content", pendingIntent);

    startForeground(1, notification);
    return START_REDELIVER_INTENT;
}

重要提醒:從 Android 8.0(API 26)開始,後台限制收緊,普通後台 Service 會很快被系統停止,長期任務必須使用前台 Service,且需要配套的 FOREGROUND_SERVICE 權限與通知渠道(NotificationChannel)。Notification.setLatestEventInfo 與 startForeground 的舊用法在高版本上均已廢棄或受限,應改用 Notification.Builder 構建通知。IntentService 也在 API 30 中被標註為 deprecated,新項目應遷移到 WorkManager。

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