I have an Android application that uses a Remote Service and I bind to it with bindService()
, which is asynchronous.
The app is useless until the service is
When I need to wait a service to be bound before doing something else I play with locks. Precisely, the ServiceConnection
owns a lock object and exposes a waitUntilConnected
method that block on the lock until a wake up signal. That notification is located in the onServiceConnected
callback.
public class MyServiceConnection implements ServiceConnection {
private volatile boolean connected = false;
private Object lock = new Object();
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
connected = true;
synchronized (lock) {
lock.notifyAll();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
connected = false;
}
public void waitUntilConnected() throws InterruptedException {
if (!connected) {
synchronized (lock) {
lock.wait();
}
}
}
}
So, for example, if an activity has to wait a service to be bound, it calls simply the waitUntilConnected
method.
protected void onStart() {
super.onStart();
bindService(myServiceIntent, myServiceConnection, Context.BIND_AUTO_CREATE);
try {
myServiceConnection.waitUntilConnected();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
I placed the waitUntilConnected
method in onStart
just as an example, but it has to be called in a different thread. I'd like to hear a more elegant way! :)