引言
在 Android 開發里,Service
?與?IntentService
?是非常關鍵的組件,它們能夠讓應用在后臺開展長時間運行的操作。不過,很多開發者僅僅停留在使用這兩個組件的層面,對其內部的源碼實現了解甚少。本文將深入剖析?Service
?和?IntentService
?的源碼,揭示它們的工作原理與區別。
Service 源碼剖析
1. Service 概述
Service
?是 Android 四大組件之一,用于在后臺執行長時間運行的操作,且不提供用戶界面。它可以通過?startService()
?啟動,也能通過?bindService()
?綁定,從而與其他組件進行交互。
2. 生命周期方法
Service
?的生命周期方法定義在?android.app.Service
?類中,主要包含?onCreate()
、onStartCommand()
、onBind()
?和?onDestroy()
。
Service
├─ onCreate() // 初始化(僅一次)
├─ onStartCommand() // 處理 startService 請求(可多次調用)
├─ onBind() // 處理 bindService 請求(返回 IBinder)
├─ onDestroy() // 釋放資源
└─ 需手動管理子線程 // 耗時操作需自行創建線程
onCreate()
:服務創建時調用,通常用于初始化操作,此方法僅調用一次。onStartCommand()
:每次調用?startService()
?啟動服務時都會調用該方法,其返回值決定了服務在被系統殺死后的重啟策略。onBind()
:當調用?bindService()
?時調用,需要返回一個?IBinder
?對象,用于與服務進行通信。onDestroy()
:服務銷毀時調用,可用于釋放資源。
A[Service 生命周期] --> B[onCreate()]B --> C{啟動方式}C -->|startService()| D[onStartCommand()]C -->|bindService()| E[onBind()]D --> F[手動調用 stopSelf()/stopService()]E --> G[解綁時 onUnbind()]F & G --> H[onDestroy()]I[IntentService 生命周期] --> J[onCreate()]J --> K[創建 HandlerThread & ServiceHandler]K --> L[onStartCommand() 調用 onStart()]L --> M[ServiceHandler 處理 Message]M --> N[調用 onHandleIntent(intent)(子線程)]N --> O[自動調用 stopSelf()]O --> P[onDestroy()(Looper.quit())]
3. 啟動流程
當調用?startService()
?方法時,最終會調用到?ActivityManagerService
?中的相關方法,它會負責創建?Service
?實例并調用其生命周期方法。
// ActivityManagerService.java
public ComponentName startService(IApplicationThread caller, Intent service,String resolvedType, int userId) {// 處理啟動服務的邏輯synchronized(this) {// ...ServiceRecord r = startServiceLocked(caller, service, resolvedType, callingPid,callingUid, userId);// ...}// ...
}
4. 注意事項
Service
?默認在主線程中運行,若在?Service
?中執行耗時操作,會導致界面卡頓。因此,若有耗時操作,應在?Service
?中手動創建子線程。
IntentService 源碼剖析
1. IntentService 概述
IntentService
?是?Service
?的子類,它是一個異步的、會自動停止的服務。它內部使用?HandlerThread
?創建了一個子線程,所有的?Intent
?都會在這個子線程中處理。
2. 關鍵源碼分析
IntentService(繼承 Service)
├─ onCreate()
│ └─ 創建 HandlerThread(子線程)
│ └─ 獲取 Looper,創建 ServiceHandler(綁定子線程 Looper)
├─ onStartCommand()
│ └─ 調用 onStart(),將 Intent 封裝為 Message 發送給 ServiceHandler
├─ ServiceHandler(Handler 子類)
│ └─ handleMessage():調用 onHandleIntent() 處理 Intent,調用 stopSelf()
├─ onHandleIntent() // 開發者需實現的核心業務邏輯(在子線程執行)
└─ onDestroy() └─ 調用 Looper.quit() 終止子線程
// android.app.IntentService
public abstract class IntentService extends Service {private volatile Looper mServiceLooper;private volatile ServiceHandler mServiceHandler;private String mName;private boolean mRedelivery;private final class ServiceHandler extends Handler {public ServiceHandler(Looper looper) {super(looper);}@Overridepublic void handleMessage(Message msg) {onHandleIntent((Intent)msg.obj);stopSelf(msg.arg1);}}public IntentService(String name) {super();mName = name;}@Overridepublic void onCreate() {super.onCreate();HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");thread.start();mServiceLooper = thread.getLooper();mServiceHandler = new ServiceHandler(mServiceLooper);}@Overridepublic void onStart(@Nullable Intent intent, int startId) {Message msg = mServiceHandler.obtainMessage();msg.arg1 = startId;msg.obj = intent;mServiceHandler.sendMessage(msg);}@Overridepublic int onStartCommand(@Nullable Intent intent, int flags, int startId) {onStart(intent, startId);return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;}@Overridepublic void onDestroy() {mServiceLooper.quit();}@Override@Nullablepublic IBinder onBind(Intent intent) {return null;}protected abstract void onHandleIntent(@Nullable Intent intent);
}
3. 關鍵流程
onCreate()
:創建一個?HandlerThread
?并啟動它,然后獲取該線程的?Looper
,創建一個?ServiceHandler
?并關聯該?Looper
。onStartCommand()
:調用?onStart()
?方法,將傳遞的?Intent
?封裝成?Message
?發送給?ServiceHandler
。ServiceHandler
?的?handleMessage()
:調用?onHandleIntent()
?方法處理?Intent
,處理完成后調用?stopSelf()
?停止服務。
4. 特點總結
- 異步處理:所有的?
Intent
?都會在子線程中處理,避免了在主線程中執行耗時操作。 - 自動停止:當所有的?
Intent
?處理完成后,IntentService
?會自動調用?stopSelf()
?方法停止服務。 - 順序處理:
IntentService
?會按照?Intent
?到達的順序依次處理,不會并發處理多個?Intent
。
Service 與 IntentService 的區別
1. 線程方面
Service
?默認在主線程中運行,若要執行耗時操作,需手動創建子線程。IntentService
?內部創建了一個子線程,所有的?Intent
?都會在該子線程中處理。
2. 停止方式
Service
?需要手動調用?stopSelf()
?或?stopService()
?來停止服務。IntentService
?在處理完所有的?Intent
?后會自動停止。
3. 處理方式
Service
?可以同時處理多個請求。IntentService
?會按順序依次處理?Intent
,不會并發處理。
總結圖表
特性 | Service | IntentService |
---|---|---|
繼承關系 | 直接繼承?ContextWrapper ,實現?ComponentCallbacks2 | 繼承自?Service ,是?Service ?的子類 |
線程環境 | 默認運行在主線程(UI 線程),需手動創建子線程處理耗時任務 | 內部創建?HandlerThread ?子線程,通過?ServiceHandler ?在子線程處理所有?Intent |
啟動后的處理邏輯 | 需重寫?onStartCommand ,手動處理業務邏輯,需手動調用?stopSelf() ?停止服務 | 自動將?Intent ?封裝為?Message ,通過?ServiceHandler ?按順序處理,處理完自動停止 |
生命周期控制 | 需手動調用?stopService() ?或?stopSelf() ?停止,或通過?onStartCommand ?返回值控制重啟策略 | 無需手動停止,處理完所有?Intent ?后自動調用?stopSelf() ?停止 |
并發處理 | 可同時處理多個?startService ?請求(需自行處理多線程同步) | 按?Intent ?接收順序串行處理,同一時間僅處理一個?Intent |
默認?onBind ?返回值 | 返回?null (需開發者自定義?IBinder ) | 直接返回?null (不支持綁定,如需綁定需自定義子類) |
適用場景 | 復雜后臺邏輯(如跨組件通信、長期運行任務) | 簡單異步任務(如網絡請求、文件操作),任務完成后自動停止 |
結論
? ? ? ? 若需要執行簡單的異步任務且任務完成后自動停止服務,可選擇?IntentService
;若需要與其他組件進行交互或同時處理多個請求,則可選擇?Service
。
感謝觀看!!!