I have an app in which the activity(MainActivity.java
) creates the object of a Java class(Algo.java
) which is supposed to do some DataBase entries and then this class has to be bounded with the service(ActionService.java
) to pass an object.
For this in the constructor of the Algo I call the context.bindService()
, but the onBind of the service is not called immediately, however bindService()
returns true
, the Algo does it's DB entries and when it's work is done and it is ready to call the service method, it still has the mBound
variable as null(in the method publishToActionService
), but after this it calls the onBound()
method and the subsequent onServiceConnected()
, now I looked around and found that it is an asynchronous call, but is there a way to ensure that onBound is called before any other execution in the code.
A code description is below:
public Algo(Context context){
this.context = context;
this.dbh = DBHelper.getInstance(context);
Intent intent = new Intent(context, ActionService.class);
boolean b = context.getApplicationContext().bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
//method to make DB calls
//---
private void publishToActionService(HackBotEvent hackBotEvent){
if((hackBotEvent != null) && (hackBotEvent.getIsLearned() != -1) && (mBound))
{
mService.fillListenedEventList(hackBotEvent);
}
}
private static ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
Log.d(LOG,"in onServiceConnected, setting mBound true");
ActionService.LocalBinder binder = (ActionService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
Log.d(LOG,"in onServiceDisconnected, setting mBound false");
mBound = false;
}
};
MainActivity.java, this is the Algo call:
Algo algo = new Algo(this);
The entire code of the Algo.java class can be seen here.