我正在尝试使用Flutter应用程序的本机代码来获取当前位置。
实现类似于Google Maps的功能似乎更可行,在该应用中,应用程序询问用户是否希望打开位置,如果他们说确定,则位置会自动打开。我已经能够成功完成此操作,但我也想将当前位置返回到颤振端。现在,我从onActivityResult()获取用户操作,然后在resultCode == RESULT_OK的情况下运行getLastLocation()方法。但是,我希望颤振结束要等到获得当前位置。我尝试使用锁定机制,但这会导致应用程序冻结。目前,我只有使用Thread.sleep(long millis)的幼稚实现,直到获得肯定的结果为止,然后将结果返回到flutter。
这是打开位置信息的代码:
private void turnLocationOn(Context context) {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this)
.checkLocationSettings(builder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
@Override
public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response =
task.getResult(ApiException.class);
} catch (ApiException ex) {
switch (ex.getStatusCode()) {
case LocationSettingsStatusCodes
.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException =
(ResolvableApiException) ex;
resolvableApiException
.startResolutionForResult(MainActivity.this,
LOCATION_SETTINGS_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOCATION_SETTINGS_REQUEST) {
if (resultCode == RESULT_OK)
{
Log.i(TAG, "User turned on location");
callResult = true;
} else if (resultCode == RESULT_CANCELED) {
Log.i(TAG, "User declined location setting request");
callResult = false;
// setCallResult(false);
}
}
}
这是设置当前位置的方法。它是LocationListener的实现:
@Override
public void onLocationChanged(Location location) {
callResult = true;
currLocation = location.getLatitude() + ", " + location.getLongitude();
}
这是Method通道,可将结果返回到flutter
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("getCurrentLocation")) {
turnLocationOn(MainActivity.this);
while (!callResult) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
result.success(currLocation);
} else {
result.notImplemented();
}
}
});
...这是从颤动的一端
final String result = await platform.invokeMethod('getCurrentLocation');
resultFromCall = "SUCCESS: $result";
debugPrint(resultFromCall);