星空网 > 软件开发 > Java

webview中java与js交互

WebView提供了在Android应用中展示网页的强大功能。也是目前Hybird app的大力发展的基础。作为Android系统的一个非常重要的组件,它提供两方面的强大的能力:对HTML的解析,布局和绘制;对JavaScript的解释和执行。Hybird App的组成是Native+H5,Native部分是java语言实现;而JavaScript是H5中必不可少的部分。因此就会遇到Java与JavaScript互相调用的情况!这里记录了一个最基本的互相调用的例了!

 

1.Native布局中添加WebView组件

1 <WebView2     android:id="@+id/wv_contacts"3     android:layout_below="@id/tv_title"4     android:layout_width="match_parent"5     android:layout_height="match_parent">6 </WebView>

 

2.初始化WebView,设置允许使用JavaScript并载入页面

1  private void initWebView() {2     mWebView = (WebView) findViewById(R.id.wv_contacts);3     WebSettings settings = mWebView.getSettings();4     settings.setJavaScriptEnabled(true);5     mWebView.loadUrl("file:///android_asset/constacts.html");6   }

 

3.java调用javaScript(mWebView.loadUrl("javascript:method(param)");)
首先定义好JavaScript函数

1 function showData(constactsData){2       var html="";3       var ullist = document.getElementById("contacts_list");4       var constactsJsonData = eval(constactsData);5       for(var i = 0; i < constactsJsonData.length; i++){6         html += "<li onclick=callPhone(\"" + constactsJsonData[i].number + "\")>" + constactsJsonData[i].name + "</li>";7       }8       ullist.innerHTML = html;9     }

然后在java调用JavaScript,放在onPageFinished回调中调用是为了保证,调用Js时,Js已全部加载完成

 1 mWebView.setWebViewClient(new WebViewClient() { 2       @Override 3       public boolean shouldOverrideUrlLoading(WebView view, String url) { 4         view.loadUrl(url); 5         return true; 6       } 7  8       @Override 9       public void onPageFinished(WebView view, String url) {10         super.onPageFinished(view, url);11         showContactsInfo();12       }13     });14 15 private void showContactsInfo() {16     String info = jsInterface.readContacts();17     mWebView.loadUrl("javascript:showData(" + info + ")");18   }

 

4.在Js中调用Java(mWebView.addJavascriptInterface(new JavaScriptInterface(), "interface");)。如代码所示,在Js中调用Java Native方法。需要将需要调用的方法所属对象转化为一个别名。将这个别名透传到JavaScript中,然后在JavaScript中通过别名访问Native方法。

首先添加别名

 1 mWebView.addJavascriptInterface(new JSInterface(this.getApplicationContext()), "jsinterface"); 
然后定义Native方法

1 public void callPhone(String number) {2     Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number));3     intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);4     mContext.startActivity(intent);5   }

最后通过别名在JavaScript中进行调用
 1 function callPhone(number){ 2 jsinterface.callPhone(number); 3 } 

 

如果便完成了Hybird App中的最基本的Java和JavaScript的通信的功能!

 




原标题:webview中java与js交互

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流