我正在使用 FusedLocationProviderClient 获取用户当前位置,一切正常,但每次打开应用程序时都会显示我获得的第一个位置,无论手机在哪里。
这种方法给了我当前的纬度和经度
private void currentCoordinate() {
//getting the user last known location
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) if (location != null) {
System.out.println(location.getLatitude() + "llloction");
getCurrentLocation(location.getLatitude(), location.getLongitude());
}
}
});
}
这是从经纬度获取地址的方法
private void getCurrentLocation(double latitude , double longitude ) {
Geocoder gCoder = new Geocoder(this);
List<Address> addresses;
try {
addresses = gCoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0){
String stringForFragment = addresses + "";
String test = stringForFragment;
//split the address text for the first time
test = test.
substring(test.indexOf("[addressLines=["),test.indexOf("],feature"));
//split the adress text for the second time
String finalTest = test.substring(test.indexOf(":") + 1);
mPlaceAutocompleteFragment.setText(finalTest);
}
} catch (IOException e) {
e.printStackTrace();
}
}