文章背景
H5最大的两大特点就是跨平台和快速迭代,所以Android项目中嵌入H5页面的场景越来越多,所以应掌握H5和原生的交互。
文章目标
实现原生和H5交互
test.html
首先准备一个简单的html页面,放在assets 目录下,在真实的项目中这个文件来自服务端。
<!DOCTYPE html>
<html>
<head>
<meta chatset="utf-8" />
<title>This is a test</title>
<style>
*{
margin: 0;
padding: 0;
}
a{
display: block;
width: 100px;
padding: 1em;
margin: 0 auto;
font-size: 1em;
color: #FFF;
background-color: highlight;
text-decoration: none;
}
</style>
</head>
<body>
<a>点击调用原生方法</a>
<script>
function showInfoFromAndroid(msg){
//把msg的内容赋值给编辑器展示
document.getElementById("helloweb").innerHTML=msg;
}
function getData(){
var result = '把编辑内容的赋值给该变量发送给Android原生';
window.AndroidObj.sendDataToAndroid(result);
}
var aTag = document.getElementsByTagName('a')[0];
aTag.addEventListener('click', function(){
getData();
return false;
}, false);
</script>
<p></p>
<div id="helloweb">
</div>
</body>
</html>
JavaScriptObject
这个主要是为js调用原生准备的接口方法,代码如下:
public class JavaScriptObject {
Context mContxt;
public JavaScriptObject(Context mContxt) {
this.mContxt = mContxt;
}
@JavascriptInterface
public void sendDataToAndroid(String message) {
Toast.makeText(mContxt, message, Toast.LENGTH_LONG).show();
}
}
值得注意的是,要想让js调用原生方法的话,方法里需要加@JavascriptInterface注解,这样js才具备调用的能力。
MainActivity
这是我们装载webview或者说是H5页面的activity。
public class MainActivity extends Activity {
TextView mTextview;
Button mBtn1,mBtn2;
WebView mWebView;
Context mContext;
@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
initViews();
//设置编码
mWebView.getSettings().setDefaultTextEncodingName("utf-8");
//支持js
mWebView.getSettings().setJavaScriptEnabled(true);
//设置背景颜色 透明
mWebView.setBackgroundColor(Color.argb(0, 0, 0, 0));
//设置本地调用对象及其接口
mWebView.addJavascriptInterface(new JavaScriptObject(mContext), "AndroidObj");
//载入js
mWebView.loadUrl("file:///android_asset/test.html");
//android中调用js中方法
mBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = "中新网北京6月22日电 近期,北京、重庆、上海、深圳等多地公布了新的社保缴费基数。由于当地平均工资的增长,各地的社保缴费基数上下限标准也普遍进行了不同程度的上调。那么,这会对你的工资收入产生什么影响呢?";
//mWebView.loadUrl("javascript:getDataFromAndroid()");
//String msg = ((EditText) findViewById(R.id.input_et)).getText().toString();
//调用js中的函数:showInfoFromJava(msg)
mWebView.loadUrl("javascript:showInfoFromAndroid('" + msg + "')");
//Toast.makeText(mContext, "调用javascript:funFromjs()", Toast.LENGTH_LONG).show();
}
});
//android中调用js中方法
mBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String json = "666";
mWebView.loadUrl("javascript:getData()");
//Toast.makeText(mContext, "调用javascript:funFromjs()", Toast.LENGTH_LONG).show();
}
});
}
public void initViews() {
mBtn1 = (Button) findViewById(R.id.btn_1);
mBtn2 = (Button) findViewById(R.id.btn_2);
mWebView = (WebView) findViewById(R.id.wv_view);
mContext = getApplicationContext();
}
}
1、 js调用原生方法
首先我们要为H5加载宿主设置本地调用对象及其接口
mWebView.addJavascriptInterface(newJavaScriptObject(mContext), "AndroidObj");
设置完之后,js就可以用这个对象调用原生的方法
function getData(){
var result = '把编辑内容的赋值给该变量发送给Android原生';
window.AndroidObj.sendDataToAndroid(result);
}
2、原生调用js方法
a、比如我们的页面中有一个js方法
function showInfoFromAndroid(msg){
//把msg的内容赋值给编辑器展示
document.getElementById("helloweb").innerHTML=msg;
}
那么原生是这样调用它:
String msg = "中新网北京6月22日电 近期,北京、重庆、上海、深圳等多地公布了新的社保缴费基数。由于当地平均工资的增长,各地的社保缴费基数上下限标准也普遍进行了不同程度的上调。那么,这会对你的工资收入产生什么影响呢?";
//mWebView.loadUrl("javascript:getDataFromAndroid()");
//String msg = ((EditText) findViewById(R.id.input_et)).getText().toString();
//调用js中的函数:showInfoFromJava(msg)
mWebView.loadUrl("javascript:showInfoFromAndroid('" + msg + "')");
对应的activity布局如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Main" >
<Button
android:id="@+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="android中调用js中方法" />
<Button
android:id="@+id/btn_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="原生获取webview上的值" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="@drawable/bg_chat_default0"
android:orientation="vertical" >
<WebView
android:id="@+id/wv_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" />
</LinearLayout>
</LinearLayout>
布局里面只有几个按钮和一下webview组件,我们的html页面就是使用webview来承载的。