2012-04-17 25 views
1

我正在使用Android服务,解释如下here。我打电话doBindService()onCreate()并试图拨打onResume()中的mBoundservice的方法之一。这是我遇到问题的地方。此时,mBoundService仍为空,大概是因为mConnection.onServiceConnected()尚未被调用。Android服务在onResume中的mBoundService null

有什么方法可以调用mBoundService的方法onResume(),或者有没有办法解决这个问题?

回答

1

它没有被明确在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(); 
} 

... ... 

希望这有助于。