How to calculate device moving speed programmatically using android

Velmurugan Murugesan
4 min readOct 1, 2020

This post for the developer who what to calculate vehicle speed using gps. I am going to explain How to get current speed using GPS in Android Device By Using the Android Location Manager.

Getting current speed can be used in many ways to the users. With the help of GPS we can find the location. By using simple calculation we can get the current moving speed.

By using this example you can calculate device moving speed programmatically.

Please check out my another tutorial to get current latitude and longitude in android.

Follow the Simple steps to get current speed using GPS

  1. Create new Project.
  2. Add permission in AndroidManifest.xml file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

3. As higher versions of Android need in-app permission so we will request app permission this way,

try {
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 101);
}
} catch (Exception e){
e.printStackTrace();
}

4. ACCESS_COARSE_LOCATION is used when we use network location provider for our Android app. But, ACCESS_FINE_LOCATION is providing permission for both providers. INTERNET permission is must for the use of network provider.

5. Check the GPS in Enabled or Not by using Location Manager.

isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

6. Create GPSManager.java and implement the GpsStatus.Listener. This will provide the callbacks to get GPS connection updates.

public class GPSManager implements android.location.GpsStatus.Listener
{
private static final int gpsMinTime = 500;
private static final int gpsMinDistance = 0;
private static LocationManager locationManager = null;
private static LocationListener locationListener = null;
private static GPSCallback gpsCallback = null;
Context mcontext;
public GPSManager(Context context) {
mcontext=context;
GPSManager.locationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
if (GPSManager.gpsCallback != null) {
GPSManager.gpsCallback.onGPSUpdate(location);
}
}

@Override
public void onProviderDisabled(final String provider) {
}

@Override
public void onProviderEnabled(final String provider) {
}

@Override
public void onStatusChanged(final String provider, final int status, final Bundle extras) {
}
};
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mcontext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mcontext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
public GPSCallback getGPSCallback()
{
return GPSManager.gpsCallback;
}

public void setGPSCallback(final GPSCallback gpsCallback) {
GPSManager.gpsCallback = gpsCallback;
}

public void startListening(final Context context) {
if (GPSManager.locationManager == null) {
GPSManager.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}

final Criteria criteria = new Criteria();

criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setSpeedRequired(true);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);

final String bestProvider = GPSManager.locationManager.getBestProvider(criteria, true);

if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) context, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
if (bestProvider != null && bestProvider.length() > 0) {
GPSManager.locationManager.requestLocationUpdates(bestProvider, GPSManager.gpsMinTime,
GPSManager.gpsMinDistance, GPSManager.locationListener);
}
else {
final List<String> providers = GPSManager.locationManager.getProviders(true);
for (final String provider : providers)
{
GPSManager.locationManager.requestLocationUpdates(provider, GPSManager.gpsMinTime,
GPSManager.gpsMinDistance, GPSManager.locationListener);
}
}
}
public void stopListening() {
try
{
if (GPSManager.locationManager != null && GPSManager.locationListener != null) {
GPSManager.locationManager.removeUpdates(GPSManager.locationListener);
}
GPSManager.locationManager = null;
}
catch (final Exception ex) {
ex.printStackTrace();
}
}

public void onGpsStatusChanged(int event) {
int Satellites = 0;
int SatellitesInFix = 0;
if (ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) mcontext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
}
int timetofix = locationManager.getGpsStatus(null).getTimeToFirstFix();
Log.i("GPs", "Time to first fix = "+String.valueOf(timetofix));
for (GpsSatellite sat : locationManager.getGpsStatus(null).getSatellites()) {
if(sat.usedInFix()) {
SatellitesInFix++;
}
Satellites++;
}
Log.i("GPS", String.valueOf(Satellites) + " Used In Last Fix ("+SatellitesInFix+")");
}
}

7. Create callback interface GPSCallback.java to receive GPS updates from GPSManager.

public interface GPSCallback
{
public abstract void onGPSUpdate(Location location);
}

8. Finally, get the current speed from the Location.

speed = location.getSpeed();
currentSpeed = round(speed,3,BigDecimal.ROUND_HALF_UP);
kmphSpeed = round((currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);

Final, MainActivity.java

public class MainActivity extends Activity implements GPSCallback{
private GPSManager gpsManager = null;
private double speed = 0.0;
Boolean isGPSEnabled=false;
LocationManager locationManager;
double currentSpeed,kmphSpeed;
TextView txtview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtview=(TextView)findViewById(R.id.info);
try {
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 101);
}
} catch (Exception e){
e.printStackTrace();
}
}
public void getCurrentSpeed(View view){
txtview.setText(getString(R.string.info));
locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
gpsManager = new GPSManager(MainActivity.this);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(isGPSEnabled) {
gpsManager.startListening(getApplicationContext());
gpsManager.setGPSCallback(this);
} else {
gpsManager.showSettingsAlert();
}
}

@Override
public void onGPSUpdate(Location location) {
speed = location.getSpeed();
currentSpeed = round(speed,3,BigDecimal.ROUND_HALF_UP);
kmphSpeed = round((currentSpeed*3.6),3,BigDecimal.ROUND_HALF_UP);
txtview.setText(kmphSpeed+"km/h");
}

@Override
protected void onDestroy() {
gpsManager.stopListening();
gpsManager.setGPSCallback(null);
gpsManager = null;
super.onDestroy();
}

public static double round(double unrounded, int precision, int roundingMode) {
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
}

Screenshots

--

--

Velmurugan Murugesan

Lead Android Engineer @htcindia | @github contributor | Blog writer @howtodoandroid | Quick Learner