当前位置: 移动技术网 > IT编程>移动开发>Android > Android实现H5与Native交互的两种方式

Android实现H5与Native交互的两种方式

2019年07月24日  | 移动技术网IT编程  | 我要评论

黄月宝,我要日,躲羊羊

前言

大家都知道在android webview使用中,经常需要h5页面和native页面进行交互,比如在网页上点击分享按钮,调用本地分享接口进行分享,分享成功后本地调用网页的javascript代码展示一条分享成功的消息。下面来看看一起看看两种实现方式是什么?

一、url拦截的方式

重写shouldoverrideurl进行url拦截,这种方式通过h5和native协商好的url格式来表明h5页面想要native进行的操作,比如拨打电话,播放视频,查看某个用户的信息等操作,每种操作对应一种url格式,比如:

“/media/image/123”代表h5要调用native查看id为123的图片;
“/webapp/close/webview”表示h5需要native关闭当前页面;
“/webapp/patient_card/?patient_id=345”表示h5要调用native显示用户345的详情页

可以通过url的parameter传递参数,并通过uri.parse进行解析。返回true表示截断对该url请求的响应。

protected webviewclient mwebclient = new webviewclient() {
 @override 
 public boolean shouldoverrideurlloading(webview view, string url) {  
  // 添加tel链接响应
  if (url.startswith("tel:")) { 
   intent intent = new intent(intent.action_dial, uri.parse(url)); 
   startactivity(intent); 
   return true;
  }

  // 添加mp4播放相应
  if (url.endswith(".mp4")) { 
   viewvideo(url); 
   return true;
  }

  // 添加图片链接响应
  if (pattern.compile("/media/image").matcher(url).find()) { 
   viewimage(url); 
   return true;
  }
  // 关闭webview
  if (pattern.compile("/webapp/close/webview").matcher(url).find()) {   
   onbackpressed(); 
   return true;
  }

  // 添加某个特殊url的响应
  if(pattern.compile("/webapp/patient_card/").matcher(url).find()) { 
   uri uri = uri.parse(url); 
   string patientid = uri.getqueryparameter("patient_id");
   viewpatientinfo(patientid);

   return true;
  }

  return super.shouldoverrideurlloading(view, url);   
};

二、javascript注入方式

相比于url拦截的方式,javascript注入的方式更加直接,native将开放给h5调用的函数注入javascript,h5通过javascript调用native函数完成操作。

1、获取webview的webviewsettings设置,调用setjavascriptenabled开启javascript调用。

websettings settings = mwebview.getsettings();
settings.setjavascriptenabled(true);

2、将需要暴露给javascript的函数前面添加@javascriptinterface注解,只有添加了该注解的函数才能被javascript调用。

public class webappinterface {
 @javascriptinterface
 public boolean method1(string param1, string param2) {
   // do something
 }

 @javascriptinterface
 public boolean method2(string param1, string param2) {
   // do something
 }
}

3、通过webview的addjavascriptinterface方法,将native方法所在的class注入到javascript中。该函数的第一个参数是注入的native对象,第二个参数是该对象的名字,javascript通过改名字访问该对象

webview webview = (webview) findviewbyid(r.id.webview);
webview.addjavascriptinterface(new webappinterface(), "interfacename");

4、这样,h5页面就可以通过下面的javascript调用native的函数了

<script type="text/javascript"> 
 function method1(param1, param2) {  
  interfacename.method1(param1, param2); 
 }
</script>

native调用javascript

native调用javascript函数的方法比较简单,通过loadurl函数进行:

// 无参数调用
contentwebview.loadurl("javascript:javacalljs()");

// 有参数调用
mwebview.loadurl("javascript:test('" + param+ "')"); // param是js的函数test()的参数

总结

以上就是这篇文章的全部内容了,希望本文的内容对各位android开发者们能带来一定的帮助,如果有疑问大家可以留言交流。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网