【发布时间】:2019-01-31 15:46:54
【问题描述】:
我有这个代码:
function getLocation() {
//function executed if started by webview
if (typeof Jinterface != 'undefined') {
Jinterface.displayGPSRequest();
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError, {
enableHighAccuracy: true
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
我需要 JavaScript 来等待函数 Jinterface.displayGPSRequest() 结束,然后再继续执行代码。我尝试了async/await,但作为从 Android Studio 中的 Java 文件调用的函数(我有我的网站的 web 视图)我不能用 async 语句命名它,因为 Java 无法识别它。有什么帮助吗?
Java 函数:
@JavascriptInterface
public void displayGPSRequest() {
Context context = getApplicationContext();
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build();
googleApiClient.connect();
final String TAG = "YOUR-TAG-NAME";
final int REQUEST_CHECK_SETTINGS = 0x1;
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);
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "All location settings are satisfied.");
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the result
// in onActivityResult().
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
break;
}
}
});
}
【问题讨论】:
-
您需要第二个函数并通过接口从您的 Java 代码中调用它。
标签: javascript java w3c-geolocation