John Kulova John Kulova - 6 months ago 64
Android Question

Determining the speed of a vehicle using GPS in android

I would like to know how to get the speed of a vehicle using your phone while seated in the vehicle using gps. I have read that the accelerometer is not very accurate. Another thing is; will GPS be accessible while seated in a vehicle. Won't it have the same effect as while you are in a building?

Here is some code I have tried but I have used the NETWORK PROVIDER instead.I will appreciate the help. Thanks...

package com.example.speedtest;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {
LocationManager locManager;
LocationListener li;
protected void onCreate(Bundle savedInstanceState) {
li=new speed();
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, li);
class speed implements LocationListener{
public void onLocationChanged(Location loc) {
Float thespeed=loc.getSpeed();
Toast.makeText(MainActivity.this,String.valueOf(thespeed), Toast.LENGTH_LONG).show();
public void onProviderDisabled(String arg0) {}
public void onProviderEnabled(String arg0) {}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}



GPS works fine in a vehicle. The NETWORK_PROVIDER setting might not be accurate enough to get a reliable speed, and the locations from the NETWORK_PROVIDER may not even contain a speed. You can check that with location.hasSpeed() (location.getSpeed() will always return 0).

If you find that location.getSpeed() isn't accurate enough, or it is unstable (i.e. fluctuates drastically) then you can calculate speed yourself by taking the average distance between a few GPS locations and divide by the time elapsed.