在另一个 class 中调用 Webview 和 loadurl

Webview and loadurl call in another class

我在从 javascriptInterface 调用 webView.loadUrl 时遇到了一些问题:

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Intent;

public class MainActivity extends Activity {

    private WebView webView;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webView);

        webView.setWebViewClient(new WebViewClient());
        JavaScriptInterface jsInterface = new JavaScriptInterface(this);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.addJavascriptInterface(jsInterface, "JSInterface");

        webView.setWebChromeClient(new WebChromeClient());


        webView.loadUrl("http://*****.com/test.php");

    }

    public class JavaScriptInterface {
        private Activity activity;

        public JavaScriptInterface(Activity activiy) {
            this.activity = activiy;
        }

        @JavascriptInterface
        public void changeTest(){
            webView.loadUrl("http://google.it");
        }
    }

}

第一个loadUrl(),onCreate中调用成功,JavascriptsInterface调用失败。但是,当我通过 Javascript 从页面调用它时,changeTest() 肯定会运行,因为我过去常常通过 intent 调用应用程序并且它加载正常。所以问题必须出在 onCreate 外部放置的 loadUrl 上。 谁能解释一下哪里出了问题,为什么会这样?

实际上你可以,因为它对我稍作修改即可。请确保 运行 UI 线程中的代码。

        @JavascriptInterface
        public void changeTest(){

            Log.d("TEST", "THIS IS THE BIGGEST TEST EVER");

            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    myWebView.loadUrl("http://google.it");
                }
            });
        }

这是在我的 html 页面中编写的 Javascript 函数的摘录:

function doChangeTest(){
        //JSInterface is the supplied name of the interface
        // in Android code: webView.addJavascriptInterface(jsInterface, "JSInterface");
        JSInterface.changeTest();
}