Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practice - Binding Service to an Activity

I have a network Service which runs in the background. I have this global variable mConnection inside the Activity

protected ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder binder) {
        serviceobject = ((NetworkService.MyBinder) binder).getService();
    }

    public void onServiceDisconnected(ComponentName className) {
        serviceobject = null;
    }
};

and then I bind the Service in the Activity's onCreate(..) using

bindService(new Intent(this, NetworkService.class), 
                 mConnection,Context.BIND_AUTO_CREATE);

The NetworkService class has an inner class MyBinder

public class MyBinder extends Binder {
    NetworkService getService() {
        return NetworkService.this;
    }
}

Now to invoke any Service method from the Activity, i use the serviceobject and I create an AsyncTask for each method invocation.(I know that invoking Service methods from the Activity nullifies the use of having Services.I use this for light methods which doesn't involve much computation)

This helps me to directly deal with the data from the Service using the serviceobject . I unbind the Service in the Activity's onDestroy()

@Override
protected void onDestroy()
{
    unbindService(mConnection);
    super.onDestroy();
}

Is this the best way of doing it or am I wrong somewhere?

like image 508
coderplus Avatar asked Nov 14 '22 05:11

coderplus


1 Answers

I think what you wanna do is to run a Remote Service. That's what ServiceConnection and bindService is used to. The idea is that your service runs in the baackground and any activity can "bind" to it and interact through in interface you define in AIDL.

The access to the service is fast so you can call method from your service from the UI thread without the use ofAsyncTask. That's one benefit.

However the implementation is a bit tedious because you must write this AIDL interface.

I recommend you to read Google's tutorial here: http://developer.android.com/guide/developing/tools/aidl.html

And then to google "Remote Service AIDL" with "tutorial" or "example".

Good Luck.

like image 109
znat Avatar answered Nov 16 '22 04:11

znat