首页 > 解决方案 > 如何在android中获取实时(实时)车速 - java

问题描述

我正在尝试开发一个用于测试目的的速度计应用程序我已经编写了能够获得速度的代码,但我不确定它是否是实时速度,因为有时我看到有一些延迟,这是我的代码:

public class MainActivity extends AppCompatActivity {

LocationManager locationManager;
LocationListener locationListener;

 public void startListening() {

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager != null) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        }
    }

}


public void updateLocationInfo(Location location){

    TextView speedtextView = (TextView) findViewById(R.id.speedTextView);

    speedtextView.setText("Current speed: " + location.getSpeed()*3600/1000);

 }


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    if (requestCode == 1) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            startListening();

        }

    }}




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            updateLocationInfo(location);

        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };


    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

    } else {

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {

            updateLocationInfo(location);

        }

    }

}
}

我还需要做什么吗?有什么特殊的方法可以获得实时速度吗?因为我使用了很多可以获得实时速度的应用程序,现在我想知道他们是怎么做到的?这可能是“公平”的 GPS 连接吗?还是我做错了?

标签: javaandroidandroid-studio

解决方案


推荐阅读