user2234594 user2234594 - 8 months ago 56
Android Question

Android java - how to make Activity wait until Service is binded?

Every example has Service bind onStart() and calling method from a Service in a while (like after onClick). Until that onClick service is being binded for sure.

I got problem that service is taking a while until it's binded and it binds asynchronously.
So if I start and Activity which needs to get some data from a Service right away - it crashes because it's not yet binded. So I need to hold my Activity waiting until it's connection finishes. How do I do that?

Answer Source

I think you want that:

On this page you can find:

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className,
            IBinder service) {
        // We've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;

    public void onServiceDisconnected(ComponentName arg0) {
        mBound = false;

The onServiceConnected method is called when the service is ready and you can do your stuff inside (or use the mBound attribute).

To bind to your service, use that:

    // Bind to LocalService
    Intent intent = new Intent(this, LocalService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);