Calling the Bound Service from Main Activity

In the last Article you learnt how to bind MainActivity with BoundService.

Time for you to call the displayDistance method to display the distance traveled. You can create a new method which will return the distance computed. This method will create a Handler and invoke the Service every second.

private void displayDistance() {
    final Handler handler = new Handler();
    handler.post(new Runnable() {
        @Override
        public void run() {
            double distance = 0;
            if(mDistanceTraveledService != null){
                distance = mDistanceTraveledService.getDistanceTraveled();
            }
            distanceTraveled.setText(String.valueOf(distance));
            handler.postDelayed(this, 1000);
        }
    });
}

Next add a TextView in the Layout XML file to display this.

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_margin="15dp"
    android:id="@+id/displayDistanceId"
    android:text="100metres"/>

Full source code is available here

 

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

Android Basics : Learn how to track Location changes by adding a LocationListener

In order to use the Location Service you need to do the following:

  • Implement LocationListener
LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        if (lastLocation == null) {
            lastLocation = location;
        }
        distanceInMetres += location.distanceTo(lastLocation);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};
  • Create LocationManager using the Listener to start tracking user location changes
LocationManager locationManager = (LocationManager)
        getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this,
        Manifest.permission.ACCESS_FINE_LOCATION) != 
            PackageManager.PERMISSION_GRANTED
        && ActivityCompat.checkSelfPermission(this,
        Manifest.permission.ACCESS_COARSE_LOCATION) != 
            PackageManager.PERMISSION_GRANTED) {
    return;
}
locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER,
        1000,
        1,
        locationListener);
  • Add Permissions to the Manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

The Source Code for this implementation is available here

Android Basics – Learn how to bind an Activity to a Bound Service

In the last Article you saw how to create a new Bound Service. The next step is to bind this Service to the Activity. In order to do this you will have to create a new Inner Class which extends Binder class. Add this in the DistanceTraveledService class that you created.

public class DistanceTravelBinder extends Binder{
    DistanceTravelBinder getBinder(){
        return DistanceTravelBinder.this;
    }
}

The purpose of this inner class will be to return an object of the Service class. When you create a Bound Service you need to create a Binder implementation. The Activity will use this to get a reference to the Service.

DistanceTravelBinder mDistanceTravelBinder = new DistanceTravelBinder();

Source Code is available here. In the next article you will learn how to use the Service class to fetch distance and return to Activity.

How being Present can help you Solve Problems

In this thought provoking TED Talk, Joi Ito narrates how a bunch of people were able to innovate by working on a Problem instead of waiting for someone to solve it.

“Remember before the internet?” asks Joi Ito. “Remember when people used to try to predict the future?” In this engaging talk, the head of the MIT Media Lab skips the future predictions and instead shares a new approach to creating in the moment: building quickly and improving constantly, without waiting for permission or for proof that you have the right idea. This kind of bottom-up innovation is seen in the most fascinating, futuristic projects emerging today, and it starts, he says, with being open and alert to what’s going on around you right now. Don’t be a futurist, he suggests: be a now-ist.

Another amazing feat by Humanity as a Solar-powered plane completes journey across Pacific Ocean.

Another amazing feat by humanity. A Solar powered plane can open the endless possibilities.

The carbon-fiber aircraft weighs just about a midsize truck.

The plane’s wings, which stretch wider than those of a Boeing 747, are equipped with 17,000 solar cells that power propellers and charge batteries. The plane runs on stored energy at night.

 

Android Basics – Learn how to use Bound Services

So far you have learnt about the Started Service, which runs indefinitely till it completes.

A Bound Service is attached to the component which invokes it. If an Activity invokes this service then the Bound Service will depend on the LifeCycle of the Activity.

An example can be if you are using location based service.

To understand this you are going to create a new Service class – DistanceTraveledService.

This Service class will track the distance the user travels. After calculating the distance it will return the value to the MainActivity class.

Let’s look at the steps needed:

  1. Create a Binder class which will connect the Service class with MainActivity.
  2. Create a LocationListener which will track location changes. Register this with DistanceTraveledService class.
  3. Create a public method getDistance() in the DistanceTraveledService. This method will be called by the MainActivity.

The following diagram shows the components needed. In the next Article you will start making the changes.

BoundService