java - 如何在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 连接吗?还是我做错了?
解决方案
推荐阅读
- ios - ReactiveSwift/ReactiveCocoa:如何使用 UIButton 禁用样式,但在 Action 正在进行时不使用?
- python - 计算并发事件的数量
- python - Conda 命令无法正常工作
- python - 将列表元素放在二维数组上的快速方法
- graph - 根据辅助变量对条形图中的条形进行排序
- google-maps - Google Maps API 捕捉标记到折线
- python - 如何根据最后一行/下一行过滤 Pandas 行?
- r - ggplot、ggsave 和 coord_map/quickmap:如何保存大型空间对象并获得正确的投影?
- xml - 是否可以在同一台机器上设置和使用 2 个不同的 security-settings.xml?
- wordpress - 配置 - Nginx 在子文件夹中有多个站点