android中未调用WebView方法



我的Web视图没有调用javascript函数,而是返回如下警告。有人能建议如何摆脱以下警告吗。

07-30 10:15:44.031: W/webview_proxy(3770): 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.

下面是我的函数。

public boolean onLongClick(View v){
    System.out.println("dfdsf");
    // Tell the javascript to handle this if not in selection mode
    //if(!this.isInSelectionMode()){
        this.getSettings().setJavaScriptEnabled(true);
        this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        this.getSettings().setPluginsEnabled(true);
        this.loadUrl("javascript:android.selection.longTouch();");
        mScrolling = true;
        //this.setJavaScriptEnabled(true);
    //}

    // Don't let the webview handle it
    return true;
}

正如警告所说,您正在调用WebViewCoreThread中的webview方法。这样修改你的代码,

public boolean onLongClick(View v){
    YourActivity.this.runOnUiThread(new Runnable() {
        public void run() {
            this.getSettings().setJavaScriptEnabled(true);
            this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            this.getSettings().setPluginsEnabled(true);
            this.loadUrl("javascript:android.selection.longTouch();");
            mScrolling = true;
        }
    });
}

警告会告诉您一切。您正在直接调用webview方法。这意味着您在WebViewCoreThread上调用它们。您必须在UI线程上调用它们,这意味着在使用此Web视图的"活动"中。

类似:

WebView wv = (WebView)findViewById(id);
wv.setJavaScriptEnabled(true);
wv.setJavaScriptCanOpenWindowsAutomatically(true);
wv.setPluginsEnabled(true);
wv.loadUrl("javascript:android.selection.longTouch();");

使用此代码我认为它会为您工作,并根据您的需要对其进行了修改##

    private WebView webView;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web);
        webView = (WebView) findViewById(R.id.web_view);
        webView.setInitialScale(1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setScrollbarFadingEnabled(false);
        webView.loadUrl("http://www.youtube.com");
    }
}

onLongClick是webview的成员吗?

您似乎无法调用线程"WebViewCoreThread"上的所有WebView方法。

您可以使用处理程序,在onLongClick中向处理程序发送消息,然后在处理程序中调用WebView方法。

我认为您必须在runOnUIThread()或使用Handler中执行onLongClick方法的代码,此警告是由于在工作线程上使用所有这些。

您可以通过Runnable使用WebView。无需使用"活动"。

    webView.post(new Runnable()
    {
        @Override
        public void run()
        {
          getSettings().setJavaScriptEnabled(true);
          getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
          getSettings().setPluginsEnabled(true);
          loadUrl("javascript:android.selection.longTouch();");
          mScrolling = true;
        }
    });

最新更新