在android中使用GPS确定车辆速度

在android中使用GPS确定车辆速度,android,gps,location,android-location,Android,Gps,Location,Android Location,我想知道坐在车上使用gps时如何使用手机获取车辆速度。我读到加速度计不是很准确。另一件事是;坐在车内时是否可以使用GPS。它不会有和你在大楼里时一样的效果吗 以下是我尝试过的一些代码,但我使用了网络提供商。我将感谢您的帮助。谢谢 package com.example.speedtest; import android.app.Activity; import android.content.Context; import android.location.Location; import a

我想知道坐在车上使用gps时如何使用手机获取车辆速度。我读到加速度计不是很准确。另一件事是;坐在车内时是否可以使用GPS。它不会有和你在大楼里时一样的效果吗

以下是我尝试过的一些代码,但我使用了网络提供商。我将感谢您的帮助。谢谢

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) {}

    }
}

GPS在车辆上工作正常。
NETWORK\u PROVIDER
设置可能不够精确,无法获得可靠的速度,而且
NETWORK\u PROVIDER
中的位置甚至可能不包含速度。您可以使用
location.hasSpeed()
location.getSpeed()
将始终返回0)

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

主要有两种计算手机速度的方法

  • 从加速度计计算速度
  • 利用GPS技术计算速度
  • 与GPS技术中的加速度计不同,如果要计算速度,必须启用数据连接和GPS连接

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

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

    制作GUI

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

    将逻辑与GUI相结合

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

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

    在“活动”旁边添加implements
    LocationListener

    LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            this.onLocationChanged(null);
    
    LocationManager.GPS\u 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"/>
    

    我们可以使用location.getSpeed()


    Thanx,我曾想过手动计算速度,直到找到便利功能。网络提供商给了我一个0.0的值。我猜这意味着它没有速度。再次感谢。location.getSpeed()的单位是多少?km/h、M/h、ft/sec、mtrs/sect文档中说,米/秒使用此功能,由于每次调用onlocation change后都会延迟获取速度。我们能做些什么使它完美无瑕呢?我扩展了
    android.location.LocationListener
    com.google.android.gms.location.LocationListener
    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
    
          }
    
    
    
    }
    
    public class MainActivity extends Activity implements LocationListener {
    
    LocationManager lm =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            this.onLocationChanged(null);
    
         @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"/>
    
      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();
                }