
- 启动服务
该服务在其他组件调用startService()时创建,然后无限期运行,且必须通过调用stopSelf()来自行停止运行。此外,其他组件也可通过调用stopService()来停止此服务。服务停止后,系统会将其销毁。
- 绑定服务
该服务在其他组件(客户端)调用bindService()时创建。然后,客户端通过 IBinder 接口与服务进行通信。客户端可通过调用unbindService()关闭连接。多个客户端可以绑定到相同服务,而且当所有绑定全部取消后,系统即会销毁该服务。(服务不必自行停止运行。)
removeConnectionLocked()移除绑定ServiceConnectionscheduleUnbindService()处理通知onUnbind()bringDownServiceIfNeededLocked(s, true, hasAutoCreate, enqueueOomAdj);中isServiceNeededLocked()判断是否还有服务绑定hasAutoCreate,若有绑定不会bringDownServiceLocked()(即handleStopService());而stopServiceLocked()传参都是false:bringDownServiceIfNeededLocked(service, false, false, enqueueOomAdj)handleStopService()通知到onDestroy();
public class ExampleService extends Service {
int startMode; // indicates how to behave if the service is killed
IBinder binder; // interface for clients that bind
boolean allowRebind; // indicates whether onRebind should be used
@Override
public void onCreate() {
// The service is being created
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return mStartMode;
}
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
return mAllowRebind;
}
@Override
public void onRebind(Intent intent) {
// A client is binding to the service with bindService(),
// after onUnbind() has already been called
}
@Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}
上面查看stopServiceLocked()传参虽然都是false,但是还是会检查hasConn = r.hasAutoCreateConnections()是否有绑定ServiceConnection

这两条路径并非完全独立。用户已经使用
startService()启动的服务,用户又通过调用 bindService() 绑定到服务。此类情况下,在所有客户端取消绑定之前,stopService() 或 stopSelf() 实际不会停止服务。