android 应用程序在 webview url 更改时崩溃

标签 android multithreading url webview crash

类似于此question ,但解决方案不适用于 mycase。

Android 应用在运行函数 webview.loadUrl 时崩溃
关闭时出现以下错误:

E/AndroidRuntime(1593): Caused by: java.lang.Throwable: Warning: A WebView method was called on thread 'WebViewCoreThread'. All WebView methods must be called on the UI thread. Future versions of WebView may not support use on other threads.

编辑:现在尝试在 runOnUiThread(new Runnable(){ }) 中运行该函数,但出现错误并且无法在上下文中输入 runOnUiThread 的位置。
完整代码如下:

   public class MyJavaScriptInterface {  
         @JavascriptInterface 
             public void androidFieldPrompt(String title, String msg, final String funct) {  
                 final EditText input = new EditText(MainActivity.this);  
                 AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);                 
                 alert.setTitle(title);  
                 alert.setMessage(msg);  
                 alert.setView(input);
                 alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {    
                    public void onClick(DialogInterface dialog, int whichButton) {  
                        String value = input.getText().toString();  

                        // ERROR IS BEING THROWN HERE
                        webView.loadUrl("javascript:window."+funct+"('"+value+"')"); 

                        return;                  
                       }  
                    });  
                alert.show();        
             }
   }

最佳答案

E/AndroidRuntime(1593): Caused by: java.lang.Throwable: Warning: A WebView method was called on thread 'WebViewCoreThread'. All WebView methods must be called on the UI thread. Future versions of WebView may not support use on other threads.

正如错误指出的那样......您正在非 UI 线程上调用 webview 方法(在点击监听器内)。

你应该使用runOnUiThread在 onClick 内部调用 Web View 方法时使用主线程

  MainActivity.this.runOnUiThread(new Runnable(){
       @Override
        public void run() {
           String value = input.getText().toString();
           webView.loadUrl("javascript:window."+funct+"('"+value+"')");
           return;
        }
 });

关于android 应用程序在 webview url 更改时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19600772/

相关文章:

java - 使用 OpenCV 将两个图像拼接在一起时抛出异常

java - 检测关闭的套接字

url - 如何使用 MongoDB/Node.js 创建友好的 URL?

css - 在 HTML/CSS 模板中查找图像的位置

android - "Speed limits are not available for this project"实现 Google Speed Limit Api 时出现问题

java - 使用 Canvas 和位图的全屏图像

java - 如何知道线程需要完成的确切时间

c# - 如何使用多维数组调用 Parallel.ForEach

java - 在 Java 中从 URL 中去除 int 的最简单方法?

Android:将值从 View 类来回传递给另一个 Activity