同意文档可能需要更清晰的说明。他们想表达的是:
- 如果您调用startService(),则服务将持续运行,直到您调用stopSerivce()(或从服务内调用 stopSelf())
- 如果您调用bindService(),则服务将持续运行,直到您调用unbindService()
- 因此,如果您同时调用startService()和bindService(),则服务将持续运行,直到您调用stopService和unbindService()。单独使用任何一个都无法停止服务。
创建了一个非常简单的Activity和Service,并运行了以下连续的start/stop/bind/unbind序列。我观察到这些调用给出了以下结果。
bind-unbind
bindService() caused:
onCreate()
onBind()
unbindService() caused:
onUnbind()
onDestroy()
开始绑定-解除绑定-停止
startService() caused:
onCreate()
onStartCommand()
bindService() caused:
onBind()
unbindService() caused:
onUnbind()
stopService() caused:
onDestroy()
开始绑定 - 停止绑定 - 解除绑定
startService() caused:
onCreate()
onStartCommand()
bindService() caused:
onBind()
stopService() caused:
-- nothing
unbindService() caused:
onUnbind()
onDestroy()
绑定-开始-停止-解绑
bindService() caused:
onCreate()
onBind()
startService() caused:
onStartCommand()
stopService() caused:
-- nothing -- still running
unbindService() caused:
onUnbind()
onDestroy()
bind-start-unbind-stop
bindService() caused:
onCreate()
onBind()
startService() caused:
onStartCommand()
unbindService() caused:
onUnbind()
stopService() caused:
onDestroy()
如您所见,在每个同时调用绑定(bind)和启动(start)的情况下,直到解除绑定(unbind)和停止(stop)都被调用时,服务才会一直运行。解除绑定/停止的顺序并不重要。
以下是在我的简单测试应用程序中从不同按钮调用的示例代码:
public void onBindBtnClick(View view) {
Intent intent = new Intent(MainActivity.this, ExampleService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
public void onUnbindBtnClick(View view) {
if (serviceIsBound) {
unbindService(serviceConnection);
serviceIsBound = false;
}
}
public void onStartBtnClick(View view) {
Intent intent = new Intent(MainActivity.this, ExampleService.class);
startService(intent);
}
public void onStopBtnClick(View view) {
Intent intent = new Intent(MainActivity.this, ExampleService.class);
exampleService.stopService(intent);
}