getLastKnownLocation возвращает Null в Android 7+ версии

108
10

Я работаю над Android-приложением, в котором я получаю Location. Ниже код работает нормально до Android 6.0, но в версиях Android 7.0 + он дает мне null на getLastKnownLocation.

try {
String country_name = null;
LocationManager lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Geocoder geocoder = new Geocoder(getApplicationContext());
for (String provider : lm.getAllProviders()) {
@SuppressWarnings("ResourceType") Location location = lm.getLastKnownLocation(provider);
if (location != null) {
try {
//,

List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

if (addresses != null && addresses.size() > 0) {
country_name = addresses.get(0).getCountryName();
/*if(country_name.equalsIgnoreCase("India")||country_name.equalsIgnoreCase("Pakistan")){*/
if(country_name.equalsIgnoreCase("India")){
selectedIndia = true;
}else{
CheckRCRCSuggestion();
}

syncLocation(location);

break;
}
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e){

}
}
}
}catch (NullPointerException ne) {
ne.printStackTrace();
}catch (Exception ne) {
ne.printStackTrace();
}

спросил(а) 2021-01-25T18:47:51+03:00 4 месяца, 3 недели назад
1
1 ответ
-4

public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}

} catch (Exception e) {
e.printStackTrace();
}

return location;
}

ответил(а) 2021-01-25T18:47:51+03:00 4 месяца, 3 недели назад
Ваш ответ
Введите минимум 50 символов
Чтобы , пожалуйста,
Выберите тему жалобы:

Другая проблема