【问题标题】:Determining the speed of a vehicle using GPS in android在android中使用GPS确定车辆的速度
【发布时间】:2023-03-25 10:00:02
【问题描述】:

我想知道如何在坐在车内使用 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) {}

    }
}

【问题讨论】:

    标签: android gps location android-location


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢,我一直想手动计算速度,直到找到便利功能。 NETWORK 提供商给了我一个 0.0 的值。我想这意味着它没有速度。再次感谢。
    • location.getSpeed() 的单位是什么?公里/小时、米/小时、英尺/秒、米/秒
    • 文档说米每秒
    【解决方案2】:

    for more information onCalculate Speed from GPS Location Change in Android Mobile Device view this link

    手机测速主要有两种方式。

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

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

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

    首先我们必须授予在 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
    
          }
    
    
    
    }
    

    如果要将 Meters/Second 转换为 kmph-1,则需要将 Meters/Second 答案从 3.6 乘以

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

    【讨论】:

    • 使用这个,获得速度会有延迟,因为每次都会在某个时间后调用 onLocationChanged。我们能做些什么让它完美无瑕?
    【解决方案3】:
    public class MainActivity extends Activity implements LocationListener {
    

    在Activity旁边添加实现LocationListener

    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"/>
    

    【讨论】:

    • 我扩展了android.location.LocationListenercom.google.android.gms.location.LocationListener也可用)
    【解决方案4】:

    我们可以使用 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();
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      • 2021-03-07
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多