我有一个应用程序,我需要在其中获取设备位置,在获取设备位置后的代码中,我将它们存储在共享首选项中,然后单击按钮后,我检索纬度和经度并在其他方法调用中使用它们,但是有时在激活 GPS 并调用“getCurrentLocation”方法(如下所列)后,我收到错误消息说存储在共享首选项中的纬度和经度值为空,即使我在调用 getCurrentLocation 方法后创建了一个持续 8 秒的加载屏幕为了等待返回值,如何让我的应用程序等待 getCurrent Location 方法直到它返回值?
假设我在 OnCreate 生命周期方法或 onButton click 上调用它,如何等待它返回值?
public void getCurrentLocation(Activity currentActivity) {
LocationRequest request = new LocationRequest();
request.setInterval(10000);
request.setFastestInterval(5000);
request.setPriority(request.PRIORITY_HIGH_ACCURACY);
FusedLocationProviderClient client =
LocationServices.getFusedLocationProviderClient(currentActivity);
int permission = ContextCompat.checkSelfPermission(currentActivity,
Manifest.permission.ACCESS_FINE_LOCATION);
if (permission == PackageManager.PERMISSION_GRANTED) {
// Request location updates and when an update is
// received, update text view
client.requestLocationUpdates(request, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location location = locationResult.getLastLocation();
if (location != null) {
// Use the location object to get Latitute and Longitude and then update your text view.
currentLocation = location;
sharedPreferences = getSharedPreferences(getPackageName() + ".prefs", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString("lat", String.valueOf(location.getLatitude()));
editor.putString("lng", String.valueOf(location.getLongitude()));
editor.apply();
// Intent i = new Intent(currentActivity,Loading.class);
// startActivity(i);
}
}
}, null);
}
}