啟動服務startService
//啟動服務,通過類名
Intent intent = new Intent(this, WiFiAutoLinkService.class);
startService(intent);
//通過字符串啟動
Intent intent = new Intent();
intent.setAction("com.launcher.app");
intent.setPackage("com.launcher");
context.startService(intent);
生命周期
onCreate() → onStartCommand() → running → stopSelf() 或 stopService() → onDestroy()
第一次: Context.startService()
?????????│
?????????├─? onCreate() ?????????(只一次)
?????????│
?????????├─? onStartCommand() ???(每次 startService 都會走)
?????????│ ???????│
?????????│ ???????├─ 后臺線程/協程干活
?????????│ ???????│
?????????│ ???????└─ stopSelf(id) 或 Context.stopService()
?????????│
?????????└─? onDestroy() ?????????(服務徹底銷毀)
注冊服務
<!-- 聲明一個可在系統插件化框架中被外部調用的后臺服務,運行在獨立進程 ":remote",用于執行 Wi-Fi 相關長連接邏輯,降低對主進程內存與生命周期的影響。 -->
<serviceandroid:name=".service.WiFiLinkService" <!-- 服務類全名 -->android:enabled="true" <!-- 默認可被系統實例化 -->android:exported="true" <!-- 允許外部(跨進程/跨應用)通過 Intent 啟動或綁定 -->android:process=":remote"> <!-- 在名為 "包名:remote" 的私有進程中運行;崩潰不影響主進程,且可單獨回收內存 --><!-- 對外暴露的調用入口:插件或系統組件通過 action 匹配啟動服務 --><intent-filter><action android:name="com.systemui.plugin.service.WiFiLinkService" /></intent-filter>
</service>
綁定服務bindService
代碼塊
// 目標插件的包名與完整服務類名(對應 <service> 聲明)
public static final String PACKAGE_NAME = "com.systemui.plugin";
public static final String CLASS_NAME = "com.systemui.plugin.service.WiFiLinkService";/* 構造顯式 Intent:指定包名 + 類名,避免隱式匹配被劫持 */
Intent intent = new Intent(CLASS_NAME); // action 字符串即為類名
intent.setPackage(PACKAGE_NAME); // 強制只綁定到該插件包/* 發起綁定:* BIND_AUTO_CREATE 表示服務未運行時會自動啟動;* 成功后會回調 onServiceConnected,失敗不回調。*/
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);/* 接收綁定生命周期的回調 */
private ServiceConnection mConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {// 已建立跨進程連接,可開始通過 IBinder 調用 AIDL 接口Log.d("TAG", "已連接");}@Overridepublic void onServiceDisconnected(ComponentName name) {// 服務異常崩潰或被系統殺死,連接斷開Log.d("TAG", "斷開連接");}
};
ActivityA
???│
???├─ bindService() ──────? onCreate()
???│ ?????????????????????????│
???│ ?????????????????????????└─ onBind() ──? ActivityA.onServiceConnected()
???│
???└─ unbindService(conn) ──? onUnbind()
????????????????????????????????│
????????????????????????????????└─ onDestroy()
多客戶端