【问题标题】:Changing Webview Url with Angular使用 Angular 更改 Webview 网址
【发布时间】:2017-09-22 15:32:18
【问题描述】:

我一直在尝试通过 AngularJs 调用函数来更改我的 webview URL,但到目前为止我没有成功。

这是我的角度类:

app.controller("speechController", function($scope){
    $scope.page = 'index.html';
    $scope.url = function(page){
        Android.receivePage();
    }
});

这是我的 Java 类:

public class MainActivity extends AppCompatActivity {


    Button b;
    CustomWebViewClient customWebViewClient;
    WebView myWebView;
    private TextToSpeech tts;
    private final int REQ_CODE_SPEECH_INPUT = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);



        myWebView = (WebView) findViewById(R.id.webView);
        myWebView.addJavascriptInterface(this, "Android");
        myWebView.setWebViewClient(new WebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("file:///android_asset/index.html");
        b= (Button)  findViewById(R.id.button);
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                receivePage();

            }
        });

    }



    @JavascriptInterface
    public void receivePage() {
        myWebView.loadUrl("file:///android_asset/index.html");
    }
}

请注意,我在 onCreate 中创建了一个按钮,只是为了调用 receivePage 函数进行测试。通过调试,我注意到 Angular 函数和按钮 onClick 函数都正确调用了 receivePage(),但是只有按钮正确更改了 URL。由于项目的需要,我需要使用 angular 来更改 webview。有谁知道我的代码为什么会这样?

【问题讨论】:

    标签: javascript java android angularjs webview


    【解决方案1】:

    我想通了,所以我会在这里发布,以防其他人遇到同样的问题。所以,问题是 JavascriptInteface 使用与 webview 不同的线程,而 webview 只接受同一线程发出的请求,我所要做的就是替换:

    @JavascriptInterface
    public void receivePage() {
        myWebView.loadUrl("file:///android_asset/index.html");
    }
    

    与:

    @JavascriptInterface
    public void receivePage() {
        myWebView.post(new Runnable() {
            @Override
            public void run() {
                myWebView.loadUrl("file:///android_asset/index.html");
            }
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-20
      • 2013-01-20
      • 1970-01-01
      • 2016-03-26
      • 2012-01-22
      • 1970-01-01
      相关资源
      最近更新 更多