android 四大组件—Service
启动服务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()
多客户端