yamspog
yamspog

Reputation: 18343

How to bind to running android service?

I'm hoping this is more of an issue with code than anything else and I'm hoping that someone out there can help track down the issue.

I have other code that starts the service with startService() and I can verify that the service is started as the debugger hits the onCreate() function of DecoderService.

However, the bindService never binds to the running service. Is this an asynchronous call and I have to wait for something to complete?

public class ResultsActivity extends Activity {

protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    Intent decoderIntent = new Intent(this,DecoderService.class);
    _isBound = bindService(decoderIntent,mConnection,Context.BIND_AUTO_CREATE);
    _textView.start(_mBoundService);
}

private boolean _isBound = false;
private DecoderService _mBoundService;

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        _mBoundService = ((DecoderService.LocalBinder)service).getService();
    }

    public void onServiceDisconnected(ComponentName className)
        _mBoundService = null;
    }
};
}

    public class DecoderService extends Service {


protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    _numCompleted = 5;
    _numTotal = 100;
}

protected int _numCompleted = 0;
protected int _numTotal = 0;


public void onCreate() {
    onHandleIntent(null);
}


@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}


// This is the object that receives interactions from clients.  See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();

public class LocalBinder extends Binder {
    DecoderService _ref = null;
    public LocalBinder()
    {
        _ref = DecoderService.this;
    }
    DecoderService getService() {
        return DecoderService.this;
    }

}
}

Upvotes: 1

Views: 6528

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006704

Is this an asynchronous call and I have to wait for something to complete?

The binding is not ready until onServiceConnected() is called on your ServiceConnection object.

Upvotes: 4

Related Questions