30

我想知道如何在使用 gps 坐在车内时使用手机获取车辆的速度。我读过加速度计不是很准确。另一件事是;坐在车辆中时是否可以访问 GPS。它不会与您在建筑物中时产生相同的效果吗?

这是我尝试过的一些代码,但我使用了 NETWORK PROVIDER。我将不胜感激。谢谢...

package com.example.speedtest;

import android.app.Activity;
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;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        li=new speed();
        locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, li);
    }
    class speed implements LocationListener{
        @Override
        public void onLocationChanged(Location loc) {
            Float thespeed=loc.getSpeed();
            Toast.makeText(MainActivity.this,String.valueOf(thespeed), Toast.LENGTH_LONG).show();
        }
        @Override
        public void onProviderDisabled(String arg0) {}
        @Override
        public void onProviderEnabled(String arg0) {}
        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}

    }
}
4

4 回答 4

32

GPS在车辆中工作正常。NETWORK_PROVIDER设置可能不够准确,无法获得可靠的速度,并且来自 的位置甚至NETWORK_PROVIDER可能不包含速度。您可以使用location.hasSpeed()(location.getSpeed()将始终返回 0) 进行检查。

如果您发现它location.getSpeed()不够准确,或者它不稳定(即波动剧烈),那么您可以通过取几个 GPS 位置之间的平均距离并除以经过的时间来自己计算速度。

于 2013-03-22T12:44:46.493 回答
31

有关从 Android 移动设备中的 GPS 位置变化计算速度的更多信息,请查看此链接

主要有两种方法可以从手机计算速度。

  1. 从加速度计计算速度
  2. 利用 GPS 技术计算速度

与 GPS Technology 的加速度计不同,如果您要计算速度,则必须启用数据连接和 GPS 连接。

在这里,我们将使用 GPS 连接计算速度。在这种方法中,我们使用 GPS 位置点在单个时间段内变化的频率。然后,如果我们有地理位置点之间的真实距离,我们就可以得到速度。因为我们有距离和时间。 速度 = 距离/时间 但是获得两个位置点之间的距离并不是很容易。因为世界在形状上是一个目标,所以两个地理点之间的距离因地而异,因角度而异。所以我们必须使用 “Haversine Algorithm”</a>

在此处输入图像描述

首先,我们必须授予在 Manifest 文件中获取位置数据的权限

制作图形用户界面 在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txtCurrentSpeed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="000.0 miles/hour"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <CheckBox android:id="@+id/chkMetricUnits"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Use metric units?"/>

然后做一个接口来获取速度

package com.isuru.speedometer;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;

public interface IBaseGpsListener extends LocationListener, GpsStatus.Listener {

      public void onLocationChanged(Location location);

      public void onProviderDisabled(String provider);

      public void onProviderEnabled(String provider);

      public void onStatusChanged(String provider, int status, Bundle extras);

      public void onGpsStatusChanged(int event);

}

使用 GPS 位置实现获取速度的逻辑

import android.location.Location;

public class CLocation extends Location {

      private boolean bUseMetricUnits = false;

      public CLocation(Location location)
      {
            this(location, true);
      }

      public CLocation(Location location, boolean bUseMetricUnits) {
            // TODO Auto-generated constructor stub
            super(location);
            this.bUseMetricUnits = bUseMetricUnits;
      }


      public boolean getUseMetricUnits()
      {
            return this.bUseMetricUnits;
      }

      public void setUseMetricunits(boolean bUseMetricUntis)
      {
            this.bUseMetricUnits = bUseMetricUntis;
      }

      @Override
      public float distanceTo(Location dest) {
            // TODO Auto-generated method stub
            float nDistance = super.distanceTo(dest);
            if(!this.getUseMetricUnits())
            {
                  //Convert meters to feet
                  nDistance = nDistance * 3.28083989501312f;
            }
            return nDistance;
      }

      @Override
      public float getAccuracy() {
            // TODO Auto-generated method stub
            float nAccuracy = super.getAccuracy();
            if(!this.getUseMetricUnits())
            {
                  //Convert meters to feet
                  nAccuracy = nAccuracy * 3.28083989501312f;
            }
            return nAccuracy;
      }

      @Override
      public double getAltitude() {
            // TODO Auto-generated method stub
            double nAltitude = super.getAltitude();
            if(!this.getUseMetricUnits())
            {
                  //Convert meters to feet
                  nAltitude = nAltitude * 3.28083989501312d;
            }
            return nAltitude;
      }

      @Override
      public float getSpeed() {
            // TODO Auto-generated method stub
            float nSpeed = super.getSpeed() * 3.6f;
            if(!this.getUseMetricUnits())
            {
                  //Convert meters/second to miles/hour
                  nSpeed = nSpeed * 2.2369362920544f/3.6f;
            }
            return nSpeed;
      }



}

将逻辑结合到 GUI

import java.util.Formatter;
import java.util.Locale;

import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class MainActivity extends Activity implements IBaseGpsListener {

      @Override
      protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            this.updateSpeed(null);

            CheckBox chkUseMetricUntis = (CheckBox) this.findViewById(R.id.chkMetricUnits);
            chkUseMetricUntis.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                  @Override
                  public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        // TODO Auto-generated method stub
                        MainActivity.this.updateSpeed(null);
                  }
            });
      }

      public void finish()
      {
            super.finish();
            System.exit(0);
      }

      private void updateSpeed(CLocation location) {
            // TODO Auto-generated method stub
            float nCurrentSpeed = 0;

            if(location != null)
            {
                  location.setUseMetricunits(this.useMetricUnits());
                  nCurrentSpeed = location.getSpeed();
            }

            Formatter fmt = new Formatter(new StringBuilder());
            fmt.format(Locale.US, "%5.1f", nCurrentSpeed);
            String strCurrentSpeed = fmt.toString();
            strCurrentSpeed = strCurrentSpeed.replace(' ', '0');

            String strUnits = "miles/hour";
            if(this.useMetricUnits())
            {
                  strUnits = "meters/second";
            }

            TextView txtCurrentSpeed = (TextView) this.findViewById(R.id.txtCurrentSpeed);
            txtCurrentSpeed.setText(strCurrentSpeed + " " + strUnits);
      }

      private boolean useMetricUnits() {
            // TODO Auto-generated method stub
            CheckBox chkUseMetricUnits = (CheckBox) this.findViewById(R.id.chkMetricUnits);
            return chkUseMetricUnits.isChecked();
      }

      @Override
      public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            if(location != null)
            {
                  CLocation myLocation = new CLocation(location, this.useMetricUnits());
                  this.updateSpeed(myLocation);
            }
      }

      @Override
      public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

      }

      @Override
      public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

      }

      @Override
      public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

      }

      @Override
      public void onGpsStatusChanged(int event) {
            // TODO Auto-generated method stub

      }



}

如果要将米/秒转换为 kmph-1,则需要将 3.6 中的米/秒答案相乘

kmph-1 的速度 = 3.6 *(ms-1 的速度)

于 2015-12-29T06:11:53.077 回答
5
public class MainActivity extends Activity implements LocationListener {

LocationListener在 Activity 旁边添加工具

LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        this.onLocationChanged(null);

LocationManager.GPS_PROVIDER, 0, 0,第一个零代表您更新值minTime的第二个零。minDistance零意味着基本上是即时更新,这可能对电池寿命不利,因此您可能需要对其进行调整。

     @Override
    public void onLocationChanged(Location location) {

    if (location==null){
         // if you can't get speed because reasons :)
        yourTextView.setText("00 km/h");
    }
    else{
        //int speed=(int) ((location.getSpeed()) is the standard which returns meters per second. In this example i converted it to kilometers per hour

        int speed=(int) ((location.getSpeed()*3600)/1000);

        yourTextView.setText(speed+" km/h");
    }
}


@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}


@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}


@Override
public void onProviderDisabled(String provider) {


}

不要忘记权限

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
于 2017-02-09T15:43:41.370 回答
1

我们可以使用 location.getSpeed();

  try {
                // Get the location manager
                double lat;
                double lon;
                double speed = 0;
                LocationManager locationManager = (LocationManager)
                        getActivity().getSystemService(LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                String bestProvider = locationManager.getBestProvider(criteria, false);
                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                Location location = locationManager.getLastKnownLocation(bestProvider);
                try {
                    lat = location.getLatitude();
                    lon = location.getLongitude();
                    speed =location.getSpeed();
                } catch (NullPointerException e) {
                    lat = -1.0;
                    lon = -1.0;
                }

                mTxt_lat.setText("" + lat);
                mTxt_speed.setText("" + speed);

            }catch (Exception ex){
                ex.printStackTrace();
            }
于 2017-05-30T07:24:37.863 回答