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