Android开发中WebView与原生JS的数据交互详解

本文来分享详细的在Android开发中,如何利用WebView与原生JS的数据交互,本教程附有代码和效果图,是一个不可多得的好教程。

关于WebView

我们知道目前android市场上的一些应用采用的开发方式大致分为三种:Native App、Web App、Hybrid App。本文主要是Hybrid App中实现的主要技术native组件与js的数据交互的理解以及实现。

Android API中提供了WebView组件来实现对html的渲染。所谓的HybridApp开发方式即是汇集了HTML5、CSS3、jS的相关开发技术,以及数据交换格式json/XML。这显然是Web开发工程师的技能。正是因为如此,众多中小企业选择了这种开发方式来减少对android开发工程师的过度依赖,至于这三种开发方式的比较与优劣不在本文考虑之列。

有了WebView这个组件,Android应用开发技术也就转嫁到html与java数据交互上来。说白了就是js与WebView的数据交互,这就是本文所要讨论的。


WebView与js的数据交互

1. WebView中载入静态页面


将WebView添加到应用中。和原生控件一样,在layout引入WebView控件。代码片段如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:orientation="horizontal" >
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent" 
/>
</LinearLayout>

载入页面:



webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("file:///file:///android_asset/page.html");

page.html存储在工程文件的assets根目录下。

2. 引入jquery mobile

引入js框架让我们编写的html页面更接近于原生控件的显示效果。目前主流的移动应用js框架有:jquery mobile和sencha touch(jquery mobile与sencha touch的选型不在本文讨论范围)。本文选择使用jquery mobile。



首先,在webview添加对js的支持:

WebSettings setting = webView.getSettings();
setting.setJavaScriptEnabled(true);//支持js

增加对中文的支持:

WebSettings setting = webView.getSettings();
setting.setDefaultTextEncodingName("GBK");//设置字符编码

设置页面滚动条风格:

webView.setScrollBarStyle(0);//滚动条风格,为0指滚动条不占用空间,直接覆盖在网页上

jquery mobile提供的标准页面模板TemplateForJQuery.html:

<!DOCTYPE html> 
<html> 
<head> 
<title>Page Title</title> 

<meta name="viewport" content="width=device-width, initial-scale=1"> 

<link rel="stylesheet" href="css/jquery.mobile-1.1.1.min.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.1.1.min.js"></script>
</head> 
<body> 

<div data-role="page">

<div data-role="header">
<h1>Page Title</h1>
</div><!-- /header -->

<div data-role="content"> 
<p>Page content goes here.</p> 
</div><!-- /content -->

<div data-role="footer">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- /page -->

</body>
</html>

页面依赖的js库、css等均放在assets目录下,目录组织结构如下:



运行应用后的截图:


下面是button 的截图,与原生控件没什么明显区别,有种以假乱真的感觉:


3. 良好的用户体验

运行我们的应用发现,在拥有大量js的页面被载入时,一直处于等待中,这是很糟糕的用户体验。可以加入进度条解决。注意到webview提供的两个方法:setWebViewClient和setWebChromeClient。其中setWebChromeClient方法正是可以处理progress的加载,此外,还可以处理js对话框,在webview中显示icon图标等。对于处理progress的代码片段如下:

webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {// 载入进度改变而触发
if (progress == 100) {
handler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
}
super.onProgressChanged(view, progress);
}
});

其中通过handler 消息机制来处理UI线程的更新:



handler = new Handler() {
public void handleMessage(Message msg) {// 定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted()){
switch (msg.what) {
case 0:
pd.show();// 显示进度对话框
break;
case 1:
pd.hide();// 隐藏进度对话框,不可使用dismiss()、cancel(),否则再次调用show()时,显示的对话框小圆圈不会动。
break;
}
}
super.handleMessage(msg);
}
};

对于setWebViewClient方法,一般用来处理html的加载(需要重载onPageStarted(WebView view, String url, Bitmap favicon))、关闭(需要重载onPageFinished(WebViewview, String url)方法)。



setWebViewClient和setWebChromeClient的作用:前者主要用于处理webView的控制问题,如加载、关闭、错误处理等;后者主要处理js对话框、图标、页面标题等。

4. 获取java中的数据

单独构建一个接口,作为处理js与java的数据交互的桥梁,本文封装的代码AndroidToastForJs.java如下:

public class AndroidToastForJs {

private Context mContext;

public AndroidToastForJs(Context context){
this.mContext = context;
}

//webview中调用toast原生组件
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}

//webview中求和
public int sum(int a,int b){
return a+b;
}

//以json实现webview与js之间的数据交互
public String jsontohtml(){
JSONObject map;
JSONArray array = new JSONArray();
try {
map = new JSONObject();
map.put("name","aaron");
map.put("age", 25);
map.put("address", "中国上海");
array.put(map);

map = new JSONObject();
map.put("name","jacky");
map.put("age", 22);
map.put("address", "中国北京");
array.put(map);

map = new JSONObject();
map.put("name","vans");
map.put("age", 26);
map.put("address", "中国深圳");
map.put("phone","13888888888");
array.put(map);
} catch (JSONException e) {
e.printStackTrace();
}
return array.toString();
}
}




Webview提供的传入js的方法:

webView.addJavascriptInterface(new AndroidToastForJs(mContext), "JavaScriptInterface");

Html页面jsonData.html设计的部分代码如下:

<script type="text/javascript">
var result = JavaScriptInterface.jsontohtml();
var obj = eval("("+result+")");//解析json字符串
function showAndroidToast(toast) 

JavaScriptInterface.showToast(toast); 
}
function getjsonData(){
var result = JavaScriptInterface.jsontohtml();
var obj = eval("("+result+")");//解析json字符串
for(i=0;i<obj.length;i++){
var user=obj[i];
document.write("<p>姓名:"+user.name+"</p>");
document.write("<p>年龄:"+user.age+"</p>");
document.write("<p>地址:"+user.address+"</p>");
if(user.phone!=null){
document.write("<p>手机号码:"+user.address+"</p>");
}
}

function list(){
document.write("<div data-role='header'><p>another</p></div>");
}
</script>
</head> 
<body> 
<div data-role="page" >
<div data-role="header" data-theme="c">
<h1>Android via Interface</h1>
</div><!-- /header -->
<div data-role="content"> 
<button value="say hello" onclick="showAndroidToast('Hello,Android!')" data-theme="e"></button>
<button value="get json data" onclick="getjsonData()" data-theme="e"></button> 
</div><!-- /content -->
<div data-role="collapsible" data-theme="c" data-content-theme="f">
<h3>I'm <script>document.write(obj[0].name);</script>,click to see my info</h3>
<p><script>document.write("<p>姓名:"+obj[0].name+"</p>");</script></p>
<p><script>document.write("<p>年龄:"+obj[0].age+"</p>");</script></p>
<p><script>document.write("<p>地址:"+obj[0].address+"</p>");</script></p>
</div>
<div data-role="footer" data-theme="c">
<h4>Page Footer</h4>
</div><!-- /footer -->
</div><!-- /page -->
</body>

点击say hello按钮运行的截图如下:




另外一篇关于webview与js交互

对于android初学者应该都了解webView这个组件。之前我也是对其进行了一些简单的了解,但是在一个项目中不得不用webview的时候,发现了webview的强大之处,今天就分享一下使用webview的一些经验。


1、首先了解一下webview。

webview介绍的原文如下:A View that displays web pages. This class is the basis upon which you can roll your own web browser or simply display some online content within your Activity. It uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, perform text searches and more.

从上面你应该了解到了基本功能,也就是显示网页。之所以我说webview功能强大是因为它和js的交互非常方便,很简单就可以实现。



2、webview能做什么?

①webView可以利用html做界面布局,虽然目前还比较少人这么使用,不过我相信当一些客户端需要复杂的图文(图文都是动态生成)混排的时候它肯定是个不错的选择。

②直接显示网页,这功能当然也是它最基本的功能。

③和js交互。(如果你的js基础比java基础好的话那么采用这种方式做一些复杂的处理是个不错的选择)。



3、如何使用webview?

这里直接用一个svn上取下的demo,先上demo后讲解。demo的结构图如下:


WebViewDemo.java

package com.google.android.webviewdemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

/**
* Demonstrates how to embed a WebView in your activity. Also demonstrates how
* to have javascript in the WebView call into the activity, and how the activity 
* can invoke javascript.
* <p>
* In this example, clicking on the android in the WebView will result in a call into
* the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code
* will turn around and invoke javascript using the {@link WebView#loadUrl(String)}
* method.
* <p>
* Obviously all of this could have been accomplished without calling into the activity
* and then back into javascript, but this code is intended to show how to set up the 
* code paths for this sort of communication.
*
*/
public class WebViewDemo extends Activity {

private static final String LOG_TAG = "WebViewDemo";

private WebView mWebView;

private Handler mHandler = new Handler();

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);

WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);

mWebView.setWebChromeClient(new MyWebChromeClient());

mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");

mWebView.loadUrl("file:///android_asset/demo.html");
}

final class DemoJavaScriptInterface {

DemoJavaScriptInterface() {
}

/**
* This is not called on the UI thread. Post a runnable to invoke
* loadUrl on the UI thread.
*/
public void clickOnAndroid() {
mHandler.post(new Runnable() {
public void run() {
mWebView.loadUrl("javascript:wave()");
}
});

}
}

/**
* Provides a hook for calling "alert" from javascript. Useful for
* debugging your javascript.
*/
final class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(LOG_TAG, message);
result.confirm();
return true;
}
}
}



demo.html

<html>
<script language="javascript">
/* This function is invoked by the activity */
function wave() {
alert("1");
document.getElementById("droid").src="android_waving.png";
alert("2");
}
</script>
<body>
<!-- Calls into the javascript interface for the activity -->
<a onClick="window.demo.clickOnAndroid()"><div style="width:80px;
margin:0px auto;
padding:10px;
text-align:center;
border:2px solid #202020;" >
<img id="droid" src="android_normal.png"/><br>
Click me!
</div></a>
</body>
</html>



main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<TextView 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="@string/intro"
android:padding="4dip"
android:textSize="16sp"
/>

<WebView
android:id="@+id/webview"
android:layout_width="fill_parent" 
android:layout_height="0dip"
android:layout_weight="1"
/>

</LinearLayout>



4、如何交互?

①android如何调用js。

调用 形式:

mWebView.loadUrl("javascript:wave()");

其中wave()是js中的一个方法,当然你可以把这个方法改成其他的方法,也就是android调用其他的方法。

②js如何调用android。

调用形式:

<a onClick="window.demo.clickOnAndroid()">

代码中的“demo”是在android中指定的调用名称,即

mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");

代码中的clickOnAndroid()是“demo”对应的对象:new DemoJavaScriptInterface() 中的一个方法。

③双向交互。

当然是把前面的两种方式组合一下就可以了。



5、讲解demo。

现在你一定了解了android和js的交互了。是时候分析一些demo了,根据上面讲的你也应该比较清楚了。具体交互流程如下:

①点击图片,则在js端直接调用android上的方法clickOnAndroid();

②clickOnAndroid()方法(利用线程)调用js的方法。

③被②调用的js直接控制html。



个人总结:利用webView的这种方式在有些时候UI布局就可以转成相应的html代码编写了,而html布局样式之类有DW这样强大的工具,而且网上很多源码,很多代码片。在UI和视觉效果上就会节省很多时间,重复发明轮子没有任何意义。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章