我正在使用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();
}
}