1

几周来我一直在尝试解决这个问题,但不知道是什么导致了这个问题。在我的项目中,我正在使用 Android Webview 的evaluateJavascript()方法,如下所示:

    this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            webView.evaluateJavascript(command, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //Parsing and taking action here
                    Log.d("Response", value);
                }
            });
        }
    });

我发送的 javascript 示例字符串是:

document.getElementById("message").value="Stuff worked!"; 

或者

document.getElementById("some-awesome-button").click(); 

虽然 10 次调用中有 9 次在onReceiveValue()方法中返回一个值,但有时我只是直接从未收到任何响应。

这种缺乏回应使连锁事件成为一场噩梦,我不知道为什么会发生这种情况。

更多数据可以避免任何其他问题:

  • 这个项目的最低 SDK 是 21,我的目标是 28。
  • 我目前没有使用任何javascriptInterfaces 并且出于一些与业务相关的原因不打算用于该项目。
  • 当我在该方法中收到来自 webview 的响应时,onReceiveValue()它通常是我刚刚设置的值,如果是单击事件,则为“null”。无论如何,问题不在于我有时会收到空值或其他值,而是有时明显缺乏响应。
  • 如代码示例所示,我肯定会按照文档在 UI 线程上运行它。
  • 每当我点击按钮时,我让服务器开发人员在控制台日志中添加一些代码,当我在onReceiveValue()方法中返回一个成功的值时,控制台日志正在工作并响应,但是当我处于无法返回的情况时响应,Web 控制台日志永远不会触发,它永远不会检测到与按钮的交互。
  • 我还尝试添加一个带有逻辑的计时器,该计时器侦听来自 webview 的响应,如果它没有收到它,则尝试再次进行相同的调用,最高可达 10 倍。当第一次调用失败时,后续尝试都不起作用。
  • 这些是我的 webview 的设置:
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAllowFileAccess(true);

似乎问题出在 Javascript Bridge 上,但我不能确定。

我的总结问题是,什么可能导致 Android WebView 的evaluateJavascript()调用不触发回调也不在onReceiveValue()方法中返回值?

4

2 回答 2

3

发生在我身上是因为我试图webView.evaluateJavascript(...)从后台线程调用。

我通过使用View#post()包装它来解决它:

webView.post(() -> webView.evaluateJavascript(...));
于 2020-04-10T11:56:16.663 回答
0

I did eventually figure out what happened here.

The shorter version is, this can happen when you have a memory leak and an object that is utilizing a semi-destroyed webview will fire off commands, but the newly-initialized webview will not receive a response because it is going to a dead listener.

If you want to prevent this from occurring, just make sure that all objects that maintain an application Context are properly disposed of or correctly reset if the activity restarts, else you have all objects that use the same Application-level context, but are using new views and callbacks entirely.

于 2019-09-06T21:08:32.143 回答