android - 如何从android devide获取纬度和经度?
问题描述
我有一个应用程序已经要求运行时权限来激活本地化权限,并且我已经准备好接收经度和纬度。我现在的问题只是从设备本身获取纬度和经度。
这是我的方法,假设该方法转到 else 语句,因为我已经有权限处理工作
if (!checkPermissions()) {
requestPermissions()
} else {
//get latitude and long here
}
解决方案
这是一个示例代码
1.LocationManager & Listener
private LocationManager locationManager;
private LocationListener locationListener;
2.设置管理器和监听器
locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
String locationProvider = LocationManager.GPS_PROVIDER;
currentLocation = locationManager.getLastKnownLocation(locationProvider);
if (currentLocation != null) {
double lng = currentLocation.getLongitude();
double lat = currentLocation.getLatitude();
Log.d("Log", "longtitude=" + lng + ", latitude=" + lat);
}