从Android GPS获取速度

时间:2013-04-17 19:46:17

标签: android service gps

我想在我的应用程序中获得LocationManager的速度。我有一个带有setSpeedRequired(true)属性的Criteria。我正在做location.getSPeed(),但它总是给我0。以下是我作为服务运行的GPS代码。

public class Tracking extends Service implements LocationListener {

    protected LocationManager locationManager;
    Location location;
    double latitude;
    double longitude;
    float velocity;
    String provider;

    private static final long minDist = 0;
    private static final long minTime = 0;
    LocationDatabaseHandler ldb;


    @Override
    public void onCreate() {
        ldb = new LocationDatabaseHandler(this);
        getLocation();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent,flags,startId);
        //because we do not want to stop the service unless we explicitly say so.
        return START_STICKY;
    }

    public Location getLocation() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setSpeedRequired(true);
        provider = locationManager.getBestProvider(criteria, false);

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDist,
                this);
        location = locationManager.getLastKnownLocation(provider);
        if(location != null) {
            onLocationChanged(location);            
        }

        return location;        
    }

    @Override
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        batteryP = getBatteryPerc();
        velocity = location.getSpeed();

        insertIntoDb(latitude, longitude, velocity, "onchanged");
    }

    public void insertIntoDb(double latitude, double longitude, float velocity, String where) {
        Date date = new Date();
        String dateStr = date.toString();

        ldb.addLocation(new Locations(latitude, longitude, dateStr, velocity));
    }

}

当我看到我的数据库时,速度始终为0.0。有什么我想念的吗?

1 个答案:

答案 0 :(得分:-2)

locationManager.requestLocationUpdates(provider,minTime,minDist,this);