Determining the speed of a vehicle using GPS in android

后端 未结 4 1731
轻奢々
轻奢々 2020-12-07 09:18

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. Anoth

4条回答
  •  感情败类
    2020-12-07 09:55

    We can use 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();
                }
    

提交回复
热议问题