android - 如何获取当前位置?
问题描述
我尝试了一些方法来获取当前用户位置(纬度、经度、..),但没有任何结果。你能帮助我吗?我最后一次尝试使用空位置:
private void getLocation() throws IOException {
if (ActivityCompat.checkSelfPermission(MainWindow.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainWindow.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else {
Location locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location locationPassive = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (locationGPS != null)
setCoordinate(locationGPS.getLatitude(), locationGPS.getLongitude());
else if (locationNetwork != null)
setCoordinate(locationNetwork.getLatitude(), locationNetwork.getLongitude());
else if (locationPassive != null)
setCoordinate(locationPassive.getLatitude(), locationPassive.getLongitude());
else
Toast.makeText(this, "Ошибка", Toast.LENGTH_SHORT).show();
}
}
private void setCoordinate(double Latitude, double Longitude) throws IOException {
latitude = String.valueOf(Latitude);
longitude = String.valueOf(Longitude);
coordinate = "Широта: " + latitude + ", долгота: " + longitude;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
String state = addresses.get(0).getAdminArea();
}
解决方案
Try to use fused location provider - https://developers.google.com/location-context/fused-location-provider.
It works really better.
推荐阅读
- r - 如何在时间序列预测中显示来自多个模型的测试数据的预测
- javascript - 使用 Vue.Js 在 Web Worker 中正确触发函数
- python - 使用 shutil.make_archive 时的目录层次结构问题
- julia - julia 1.0 Integer Div 符号的 unicode 是什么
- javascript - 阻止 HTML5 Canvas 在 Phonegap App 中的触摸/滑动事件上滚动整个页面?
- android - 我可以在 android 上使用 tfidf 矢量化器吗
- mysql - 如何从终端从远程服务器下载 mySQL 表
- javascript - Angular-如何使用重复组件路由父/子?
- javascript - ReactJS/Javascript:将项目列表呈现到屏幕上
- javascript - 内容更改时的瞬时文本突出显示