Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When can you call a bound service in the Android Activity lifecycle?

I am quite new to Android dev and struggling with with the concept of bound services

I have bound a service to an Activity in the onCreate method of the activity

startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

mConnection is a ServiceConnection object for which I have overridden the onServiceConnected callback method in an anonymous class

In the callback, mService (which is a class member of type LibraryService, LibraryService is my subclass of Service) is set to reference the LibraryService object we are binding to:

mService = binder.getService();

I thought that after the call to bindService in onCreate I would then be able to call the LibraryService through mService reference, but it is still set to null at this point indicating that the onServiceConnected callback has not been executed.

I have tried to print the value of a string generated by an mService method using Log:

if (mService != null) {
    Log.d(LOG_TAG, "In onCreate getLogFileName string value: " + mService.getLogFileName("pulse"));             
} else {
    Log.d(LOG_TAG, "In onCreate getLogFileName string value: null");                
}

as I mentioned - it was still null in onCreate, I then added the same log code to onStart and onResume but mService is still null

My question is when does that callback get executed? I would have thought it would have to occur within the body of the onCreate method but clearly not. I think I need a few pointers in how/when callbacks are executed by the Android system

I know the callback does get executed as I have put a breakpoint on the statement where mService is instantiated and it hits that statement. I just don't understand when its occuring, i.e. how do I know when its OK to assume mService has been set? Can I only access it within the body of the OnServiceConnected callback?

like image 943
bph Avatar asked Dec 05 '25 23:12

bph


1 Answers

Service binding is asynchronus and, as such, you have to handle this with a little of synchronization. Hence, after calling bind service you could do something like

synchronized(this){
   while(mBoundInstance == null)
      this.wait();
}

in onServiceConnected:

synchronized(this){
   this.notify(); //wakes up thread: now mBoundInstance is 100% != null
}

Note that is good putting that wait in an asyncTask, so that ui does not get frozen.

like image 152
user1610075 Avatar answered Dec 07 '25 17:12

user1610075



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!