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

 

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

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 )

Google+ photo

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

Connecting to %s