`
shuechaolau
  • 浏览: 33585 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

android中js与java的相互调用

 
阅读更多

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

        //设置字符集编码  

        webView.getSettings().setDefaultTextEncodingName("UTF-8");  

        //开启JavaScript支持  

        webView.getSettings().setJavaScriptEnabled(true);  

        

 

        class JsObject {

            @JavascriptInterface

            public String toString() { return "hehe"; }

         }

        webView.addJavascriptInterface(new JsObject(), "hehe"); 

        webView.loadData("", "text/html", null);

 

        // 支持alert

        webView.setWebChromeClient(new WebChromeClient() {  

            @Override  

            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {  

                AlertDialog.Builder b2 = new AlertDialog.Builder(HTMLActivity.this)  

                        .setMessage(message)  

                        .setPositiveButton("ok",  

                                new AlertDialog.OnClickListener() {  

                                    @Override  

                                    public void onClick(DialogInterface dialog,  

                                            int which) {  

                                        result.confirm();  

                                    }  

                                });  

          

                b2.setCancelable(false);  

                b2.create();  

                b2.show();  

                return true;  

            }  

        });

 

webView.setWebViewClient(new WebViewClient());

        

        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

 

try{

        Thread.currentThread().sleep(1000L);

        webView.loadUrl("javascript:alert(window.hehe.toString())");  

        }catch(Exception e){

       

        }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics