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() {
    public void onServiceConnected(ComponentName name, IBinder service) {
        DistanceTraveledService.DistanceTravelBinder distanceTravelBinder = 
        mDistanceTraveledService = distanceTravelBinder.getBinder();
        bound = true;

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

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

protected void 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: Logo

You are commenting using your 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: