Android Basics : Learn how to bind a Bound Service to an Activity using ServiceConnection

In the previous Article you saw how to add the LocationListener to the Service class. You created a method getDistanceTraveled to return the distance.

Next step is to call this method from the MainActivity. So how to do this ?

You need to create a ServiceConnection object and implement its methods.

ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        DistanceTraveledService.DistanceTravelBinder distanceTravelBinder = 
                (DistanceTraveledService.DistanceTravelBinder)service;
        mDistanceTraveledService = distanceTravelBinder.getBinder();
        bound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        bound = false;
    }
};

Once you have the ServiceConnection object you need to create an intent and call bindService method.

@Override
protected void onStart(){
    super.onStart();
    Intent intent = new Intent(this, DistanceTraveledService.class);
    bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}

Source code is available here

Author: Ankur

I am Enthusiastic about Learning new things and sharing my Knowledge. I like programming and have a pretty good background in Computer Science.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: