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