Android的webview加载本地html、assert内html和网络URL&&& JS与移动端webview的相互交互

来源:互联网 发布:sqlserver 商业智能 编辑:程序博客网 时间:2024/06/06 17:16


Android的webview加载本地html、assert内html和网络URL:


//打开本包内asset目录下的test.html文件

wView.loadUrl(" file:///android_asset/test.html ");  


//打开本地sd卡内的kris.html文件
wView.loadUrl("file:///mnt/sdcard/test.html");
WebView.loadUrl("file://"+"/mnt/sdcard/"+"index.html");
wView.loadUrl("content://com.android.htmlfileprovider/sdcard/kris.html");


//打开指定URL的html文件

wView.loadUrl("http://www.krislq.com/");





JS与移动端webview的相互交互:


随着h5在移动端的普及,移动端对webview的使用越来越平凡,有的界面也不仅仅局限于网页的显示,很多时候就要涉及到webview与javascript代码之间的交互,这对于移动端工程师和web端工程师都是一个挑战,下面来总结下它们之间的交互和注意事项。

1.先说js中调用android代码:下面是我写的一段简单的js代码:放在了assets文件夹下了(注意若使用的是AS这个IDE,assets文件夹应放在src/main目录下)

<!DOCTYPE html><html>   <head>      <meta charset="utf-8">      <title>葛夫锋</title>            <script>         function callAndroid(){            test.hello("js调用了android中的hello方法");         }      </script>   </head>   <body>      <button type="button" id="button1" onclick="callAndroid()">js调用android中的代码</button>   </body></html>

代码非常简单,页面中就一个按钮,点击这个按钮调用callAndroid函数,这里需注意callAndroid函数中的语句是android中对外的的一个函数,在android中的代码:

{    ...       webSettings.setJavaScriptEnabled(true);    webView.addJavascriptInterface(this, "test");//对应js中的test.xxx    webView.loadUrl("file:///android_asset/js_web.html");}@JavascriptInterfacepublic void hello(String msg){//对应js中xxx.hello("")    Log.e("webview","hello");    Toast.makeText(this,msg,Toast.LENGTH_LONG).show();}

这里需注意的是hello函数加上注解@javascriptInterface,这样点击html中的按钮就会调用android中的hello方法了。

2.android调用js代码:

js代码如下:

<script>   function callJS(){      alert("android调用了js中的callJS方法");   }</script>

android代码如下:

public void click(View view){    webView.post(new Runnable() {        @Override        public void run() {            webView.loadUrl("javascript:callJS()");        }    });}

当android中的按钮被点击时会触发click方法,然后执行webview.loadUrl("javascript:callJS()"),然后js中正好有callJS这个方法,然后alert()就会被执行,这里需要注意的是在android的代码中我没有直接写

webView.loadUrl("javascript:callJS()");

而是加了一个post(new Runble),若不加的话js代码是不被调用的。

好了,是不是so easy,android与js的简单交互就是这样,欢迎补充



0 0
原创粉丝点击