我正在开发Android应用程序,我在其中获得了位置。下面的代码在Android 6.0之前工作正常,但在Android 7.0 +版本中,它在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();
}
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;
}