user1049280 user1049280 - 3 months ago 17
Android Question

bind/unbind service example (android)

can you give me a simple example of application with background service which uses bind/unbind methods to start and stop it? i was googling for it for an halfhour, but those examples uses startService/stopService methods or are very difficult for me. thank you.

Answer

you can try use this code:

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        Log.d(LOG_TAG, "onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG, "onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code, I think it is not necessary to explain what is it 
    mContext.bindService(i, mServerConn, Context.BIND_AUTO_CREATE);
    mContext.startService(i);
}

public void stop() {
    mContext.stopService(new Intent(mContext, ServiceRemote.class));
    mContext.unbindService(mServerConn);
}