它没有被明确在official dev guide是bindService()实际上是一个异步调用说:
客户端可以通过调用bindService绑定到服务()。当它这样做时,它必须提供ServiceConnection的实现,它监视与服务的连接。 bindService()方法立即返回没有值,但是当Android系统创建客户端和服务之间的连接时,它会调用ServiceConnection上的onServiceConnected()以提供客户端可以用来与服务进行通信的IBinder。
有一个滞后(虽然瞬间,但仍然滞后)调用bindService()之后和之前的系统准备/实例化一个可用的服务实例(NOT NULL),并把它背在ServiceConnection.onServiceConnected()回调。 onCreate()和onResume()之间的时间间隔太短而无法克服延迟(如果活动是第一次打开的话)。
假设您想在onResume()中调用mBoundservice.foo(),常用的解决方法是在第一次创建活动时设置布尔状态并在onResume()方法中调用onServiceConnected()回调把它当且仅当状态设置,有条件的控制代码执行,即调用mBoundservice.foo()的基础上different Activity lifecycle:
LocalService mBoundservice = null;
boolean mBound = false;
... ...
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mBoundservice = binder.getService();
mBound = true;
// when activity is first created:
mBoundservice.foo();
}
... ...
};
... ...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// call bindService here:
doBindService();
}
@Override
protected void onResume() {
super.onResume();
// when activity is resumed:
// mBound will not be ready if Activity is first created, in this case use onServiceConnected() callback perform service call.
if (mBound) // <- or simply check if (mBoundservice != null)
mBoundservice.foo();
}
... ...
希望这有助于。