Thursday, May 3, 2012

Calculate Device Moving Speed Programmatically

so this evening i would like to share with you new thing what i have learn..

some time we need to calculate moving speed of our android mobile device.

this example will calculate the location coordinates latitude-longitude after every 5 seconds gap.
and then calculate the speed of device in m/s.
all work done in background by the service.

so i we need to do is install this app into mobile and close now it started a background service
and calculate the speed forever..
[you can create without any activity also, but i have created an activity ans started the service from activity]

let's begin the coding, first of all we need to create a simple project having single activity like this
package com.rdc;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class DeviceMovingSpeed extends Activity// implements Runnable
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        Log.v("Debug", "Activity started..");
        Intent myIntent=new Intent(this,MyService.class);  

Now we need to create a service where we will handle all the stuff creating a thread Getting current location calculating coordinates latitude-longitude calculating distance and device moving speed
package com.rdc;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service
 private LocationManager locManager;
 private LocationListener locListener = new myLocationListener();
 static final Double EARTH_RADIUS = 6371.00;
 private boolean gps_enabled = false;
 private boolean network_enabled = false;
 private Handler handler = new Handler();
 Thread t;
   public IBinder onBind(Intent intent) {return null;}
   public void onCreate() {}
   public void onDestroy() {}
   public void onStart(Intent intent, int startid) {}   
 public int onStartCommand(Intent intent, int flags, int startId){
 Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT).show();
 final Runnable r = new Runnable()
 {   public void run() 
   Log.v("Debug", "Hello");
   handler.postDelayed(this, 5000);
  handler.postDelayed(r, 5000);  
       return START_STICKY; 
   public void location(){
 locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
 catch(Exception ex){}
 network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);    
 catch(Exception ex){}
 Log.v("Debug", "in on create.. 2");   
 if (gps_enabled) {
 Log.v("Debug", "Enabled..");
 if (network_enabled) {
 Log.v("Debug", "Disabled..");
 Log.v("Debug", "in on create..3");
   private class myLocationListener implements LocationListener
      double lat_old=0.0;
      double lon_old=0.0;
      double lat_new;
      double lon_new;
      double time=10;
      double speed=0.0;
 public void onLocationChanged(Location location) {   
 Log.v("Debug", "in onLocation changed..");   
 //String Speed = "Device Speed: " +location.getSpeed();
 lon_new =location.getLatitude();
 String longitude = "Longitude: " +location.getLongitude();
 String latitude = "Latitude: " +location.getLatitude();    
 double distance =CalculationByDistance(lat_new, lon_new, lat_old, lon_old);    
 speed = distance/time;     
 Toast.makeText(getApplicationContext(), longitude+"\n"+latitude+"\nDistance is: "
   +distance+"\nSpeed is: "+speed , Toast.LENGTH_SHORT).show();
 public void onProviderDisabled(String provider) {}
 public void onProviderEnabled(String provider) {}
 public void onStatusChanged(String provider, int status, Bundle extras) {}    
   public double CalculationByDistance(double lat1, double lon1, double lat2, double lon2) {
  double Radius = EARTH_RADIUS;
  double dLat = Math.toRadians(lat2-lat1);  
  double dLon = Math.toRadians(lon2-lon1);  
  double a = Math.sin(dLat/2) * Math.sin(dLat/2) +  
  Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *  
  Math.sin(dLon/2) * Math.sin(dLon/2);  
  double c = 2 * Math.asin(Math.sqrt(a));  
  return Radius * c;

now come to AndroidManifest.xml



okay!! that's it.. now run the application toast will appear to say :-
"current coordinates"
"distance if device is moving"
"and speed of device in m/s (meter/seconds)"


 I'd love to hear your thoughts!


  1. Hello,

    Can I please get your email so I can ask you some question about android application development in private?

    Or email me at



  2. Hi,

    This is exactly what I am after. I cant seem to get it to work though. It comes up with just a blank screen. Do I need to add anything else to my main.xml other than just the standard relative layout?

    Many Thanks


  3. Superb blog! Do you have any tips and hints for aspiring
    writers? I'm hoping to start my own blog soon but I'm a little lost on everything.
    Would you suggest starting with a free platform like Wordpress or go for a paid option?
    There are so many options out there that I'm completely confused .. Any suggestions? Cheers!

    my blog - how much should you weigh