在我的应用中,我创建了AsyncTask
,在onPreExecute
中,我正在检查权限,在onPostExecute
中,我正在处理结果,在doInBackground
中,实际上正在检查位置。
我曾经使用标准代码:
LocationManager mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location mLocation;
if (mLocationManager != null) {
if (gps) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} else {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
latitude = mLocation.getLatitude();
longitude = mLocation.getLongitude();
}
之后:
Geocoder mGeocoder = new Geocoder(getApplication(), Locale.getDefault());
List<Address> adress;
adress = mGeocoder.getFromLocation(latitude, longitude, 1);
location = adress.get(0).getLocality();
问题是我认为我应该更改并使用新的位置API,FusedLocationProvider
,当我这样做时,我得到了lat
和long
,但是Geocoder
不断抛出IOException
。坐标直到小数点后四位都是一样的,这可能就是为什么我无法获得城市名称的原因吗?
我使用了这2种方法,而第二种方法不会导致Geocoder
抛出IOE
,但仍然无法获得我的地址:
FusedLocationProviderClient mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
Location currentLocation = (Location) task.getResult();
if (currentLocation != null) {
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
}
}
});
//2nd
location.addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
});