I am using an android service as explained here. I am calling doBindService() in onCreate() and trying to call one of mBoundservice‘s methods in onResume(). This is where I run into an issue. At this point, mBoundService is still null, presumably because mConnection.onServiceConnected() hasn’t yet been called.
Is there some way to be able to call methods of mBoundService in onResume(), or is there no way around it’s being null at that point?
It hasn’t been clear stated in the official dev guide that bindService() is actually an asynchronous call:
There is a lag (although instantaneous but still a lag) after calling bindService() and before system prepare/instantiate a usable service instance (not NULL) and hand it back in ServiceConnection.onServiceConnected() callback. the time interval between onCreate() and onResume() is too short to overcome the lag (in case if activity is opened first time).
Suppose you want to call mBoundservice.foo() in onResume(), a common workaround is call it in onServiceConnected() callback when activity is first created, and set a boolean state, and in onResume() method, only call it iff the state is set, to conditional control the code execution i.e. calling mBoundservice.foo() based on different Activity lifecycle:
Hope this helps.