我一直在应用程序中工作,我需要获取用户的当前位置。同样,我在清单文件中添加了 COARSE_LOCATION 和 FINE_LOCATION 权限。
我还在应用程序中添加了运行时权限,并检查了应用信息中是否启用了权限。
我一直在使用以下代码来获取用户的位置。
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(new Criteria(), true);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} else {
Location locations = locationManager.getLastKnownLocation(provider);
List<String> providerList = locationManager.getAllProviders();
if (null != locations && null != providerList && providerList.size() > 0) {
double longitude = locations.getLongitude();
double latitude = locations.getLatitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> listAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if (null != listAddresses && listAddresses.size() > 0) {
cityname = listAddresses.get(0).getLocality();
countryname = listAddresses.get(0).getCountryName();
regionname = listAddresses.get(0).getSubLocality();
System.out.println("Location updates = " + cityname + regionname + countryname);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这段代码在某些设备上运行良好(REDMI NOTE 3,REDMI NOTE 4,MOTO E),在某些设备中它返回null(SAMSUNG J7,MOTO G)。
我在哪里出错了?任何建议对我的项目和学习都非常满意。
答案 0 :(得分:0)
我遇到了同样的问题。我将locationManager.getLastKnownLocation(provider);
代码放在循环中,直到我获得当前位置的纬度和经度。见下面的代码:
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location location = null;
do {
location = getLastKnownLocation();
}
while (location == null);
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = null;
try {
l = locationManager.getLastKnownLocation(provider);
} catch (SecurityException e) {
e.printStackTrace();
}
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
答案 1 :(得分:0)
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
do{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}while (location == null);
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
Log.d("locationLinster",message);
}else{
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
Log.d("locationLinster",message);
}
这确实有助于启动提供程序...如果我们第一次遇到此问题,则需要时间。但是一旦启动,它就像梦一样。
感谢@RG