3.3 Service 的启动方式
在 Android 中,Service 主要有两种启动方式:
3.3.1 普通启动(startService)
- 使用
startService()
启动,Service 不会和 Activity 绑定。 - 适用于 后台任务处理,如 下载文件、同步数据。
- 任务完成后,需要 手动调用
stopSelf()
关闭 Service。
Intent intent = new Intent(this, MyBackgroundService.class);
startService(intent);
3.3.2 绑定启动(bindService)
- 通过
bindService()
绑定 Service,可 与 Activity 进行交互。 - 适用于 客户端 - 服务器 模型,例如 音乐播放器、蓝牙连接。
- 当所有绑定的组件(如
Activity
)解绑后,Service 会自动销毁。
示例代码(绑定 Service):
public class MyBoundService extends Service {
private final IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
MyBoundService getService() {
return MyBoundService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public String getMessage() {
return "Hello from Service!";
}
}
Activity 绑定 Service
private MyBoundService myService;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MyBoundService.LocalBinder binder = (MyBoundService.LocalBinder) service;
myService = binder.getService();
Log.d("Service", myService.getMessage());
}
@Override
public void onServiceDisconnected(ComponentName name) {
myService = null;
}
};
Intent intent = new Intent(this, MyBoundService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
3.4 Service 的生命周期
生命周期方法 | 触发时机 | 适用场景 |
| Service 第一次创建 | 初始化资源,如数据库、线程 |
|
| 开始后台任务,如下载文件 |
|
| 提供绑定接口 |
| 解绑 | 释放绑定资源 |
| Service 被销毁 | 释放资源,停止线程 |
生命周期流程
- 启动 Service
onCreate() → onStartCommand()
- 绑定 Service
onCreate() → onBind()
- 停止 Service
onDestroy()