【问题标题】:Wait for a function to end等待函数结束
【发布时间】: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


【解决方案1】:

displayGPSRequest 需要提供一种知道何时完成的方法。如果当前没有,您需要对其进行编辑以添加一个(或使用轮询,这不是一个好主意)。

通常的方法是:

  1. 通过承诺。

  2. 通过原始回调。

所以如果displayGPSRequest 返回一个承诺(或者你编辑它):

JInterface.displayGPSRequest()
    .then(function() {
        // The code that should run when it finishes
    })
    .catch(function() {
        // It failed
    });

如果displayGPSRequest 使用原始回调(或者您将其编辑为),则:

JInterface.displayGPSRequest(function() {
    // The code that should run when it finishes
    // It should also have some way of telling the callback it failed
});

如果它没有提供一种在完成时通知您并且您无法添加的方法,则您必须使用轮询来解决它产生的一些副作用,这在很大程度上是不得已的情况:

var timer = setInterval(function() {
    if (/*...the side effect is present and so you know it's done..*/) {
        clearInterval(timer);
        timer = 0;
        // The code that should run when it finishes
    }
}, 100); // 100ms = ten times a second, adjust as appropriate
setTimeout(function() {
    if (timer) {
        // Give up
        clearInterval(timer);
        timer = 0;
    }
}, 5000); // 5000ms = five seconds

【讨论】:

  • 感谢您的回答,但我无法使用这两种方法,因为我不知道如何将 java 与 javascript 接口。我添加了我的 java 函数的代码,你能做一些事情来为该代码添加一个可以由 javascript 调用的承诺吗?再次感谢您
猜你喜欢
  • 2018-01-17
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多