如何在Android中获得实时(实时)车速 - java

时间:2018-06-15 22:16:36

标签: java android android-studio

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

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连接?或者我做错了吗?

0 个答案:

没有答案