欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android与H5互调详细介绍

程序员文章站 2023-01-05 21:41:07
android与h5互调详细介绍    微信,微博,微商,qq空间,大量的软件使用内嵌了h5,这个时候就需要了解android如何更h5交互的了;有些...

android与h5互调详细介绍

   微信,微博,微商,qq空间,大量的软件使用内嵌了h5,这个时候就需要了解android如何更h5交互的了;有些外包公司,为了节约成本,采用android内嵌h5模式开发,便于在ios上直接复用页面,最终解决成本。

        为什么学android也要学h5?

android很多软件都有内嵌h5的,有什么用处、优势?节约成本,提高开发效率。

实现的原理是什么?

        本质是:java代码和javascript调用

案例一:java与js简单互调

        首先,在android代码中加载h5页面:

private void initwebview() {
  webview = new webview(this);
  websettings websettings = webview.getsettings();
  //设置支持javascript脚步语言
  websettings.setjavascriptenabled(true);

  //支持双击-前提是页面要支持才显示
  websettings.setusewideviewport(true);

  //支持缩放按钮-前提是页面要支持才显示
  websettings.setbuiltinzoomcontrols(true);

  //设置客户端-不跳转到默认浏览器中
  webview.setwebviewclient(new webviewclient());

  //加载网络资源
  //webview.loadurl("http://atguigu.com/teacher.shtml");
  webview.loadurl("file:///android_asset/javaandjavascriptcall.html");

  //显示页面
  setcontentview(webview);
 }

        javaandjavascriptcall.html:

<html>
<head>
 <meta http-equiv="content-type" content="text/html;charset=utf-8">
 <script type="text/javascript">

 function javacalljs(){
   document.getelementbyid("content").innerhtml += 
    "<br\>java调用了js无参函数";
 }

 function javacalljs(arg){
   document.getelementbyid("content").innerhtml =
    ("欢迎:"+arg );
 }


 function showdialog(){
  alert("谷粉们你好,我是来自javascript");
 }
 </script>
</head>
<body>
<div align="left" id="content"> 谷粉</div>

<input type="button" value="点击android被调用" onclick="window.android.showtoast()" />
</body>
</html>

        java调用javascript:

/**
 * java调用javascript
 * @param numebr
 */
private void login(string numebr) {
 webview.loadurl("javascript:javacalljs("+"'"+numebr+"'"+")");
 setcontentview(webview);
}

        javascript调用java

 /**
  * js可以调用该类的方法
  */
 class androidandjsinterface{
  @javascriptinterface
  public void showtoast(){
   toast.maketext(javaandjsactivity.this, "我被js调用了", toast.length_short).show();
  }
 }
 //与此同时需要在webview当中注册,后面的“android”与html中的对应:
 webview.addjavascriptinterface(new androidandjsinterface(),"android");
 //html里的点击事件实现:<br>
 <input type="button" value="点击android被调用" onclick="window.android.showtoast()" />

案例二:h5页面调用android播放视频

        了解了简单调用,下面讲的这个也就简单了:

        1_jscalljavavideoactivity的布局和实例化控件

<?xml version="1.0" encoding="utf-8"?>
<relativelayout 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"
 tools:context="com.atguigu.androidandh5.jscalljavavideoactivity">

 <webview
  android:id="@+id/webview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

</relativelayout>

        2_实例化控件并且配置

public class jscalljavavideoactivity extends activity {

 private webview webview;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_js_call_java_video);
  webview = (webview) findviewbyid(r.id.webview);
  websettings websettings = webview.getsettings();
  //设置支持javascript脚步语言
  websettings.setjavascriptenabled(true);

  //支持双击-前提是页面要支持才显示
//  websettings.setusewideviewport(true);

  //支持缩放按钮-前提是页面要支持才显示
  websettings.setbuiltinzoomcontrols(true);

  //设置客户端-不跳转到默认浏览器中
  webview.setwebviewclient(new webviewclient());

  //加载网络资源
//  webview.loadurl("http://atguigu.com/teacher.shtml");
   webview.loadurl("file:///android_asset/realnetjscalljavaactivity.htm");

 }

 }

        3_加载页面

//加载本地资源 
 webview.loadurl("file:///android_asset/realnetjscalljavaactivity.htm");

        4_参照js代码写java被调用代码

url = "/mobiles/interactive/65411";
var videourl = "http://10.0.2.2:8080/yellow.mp4";
var itemid = "65411";
var itemdesc = "1级单杀小龙,5级单杀峡谷先锋!"; 
var itempic = "http://avatar.anzogame.com/pic_v1/lol/news/20160507/spic65411h572d6eaf.jpg";
var itemtitle = "6.9玛尔扎哈op套路教程";
var obj_play = document.getelementbyid('play');
var obj_download = document.getelementbyid('download');
if(obj_play != null) {
 obj_play.ontouchstart = function() {
  this.classname = 'inter_click';
  javascript:android.playvideo(itemid, videourl, itemtitle);
  ajaxrequest('/stat/item', "post", true, {type:'play', id:itemid});
 }
 obj_play.ontouchend = function() {
  this.classname = 'inter';
 }
}

        5_配置javascript接口

//设置支持js调用java
webview.addjavascriptinterface(new androidandjsinterface(),"android");

        6_javascript接口类

class androidandjsinterface {
 /**
  * 该方法将被js调用
  * @param id
  * @param videourl
  * @param tile
  */
 @javascriptinterface
 public void playvideo(int id,string videourl,string tile){
  //调起系统所有播放器
  intent intent = new intent();
  intent.setdataandtype(uri.parse(videourl),"video/*");
  startactivity(intent);
 }
}

案例三:h5页面调用android拨打电话

        1_jscalljavacallphoneactivity布局

<?xml version="1.0" encoding="utf-8"?>
<relativelayout 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"
 tools:context="com.atguigu.androidandh5.jscalljavavideoactivity">

 <webview
  android:id="@+id/webview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

</relativelayout>

        2_初始化webview并且配置

private webview webview;

 @override
 protected void oncreate(bundle savedinstancestate) {
  super.oncreate(savedinstancestate);
  setcontentview(r.layout.activity_js_call_java_video);
  webview = (webview) findviewbyid(r.id.webview);
  websettings websettings = webview.getsettings();
  //设置支持javascript脚步语言
  websettings.setjavascriptenabled(true);

  //支持双击-前提是页面要支持才显示
//  websettings.setusewideviewport(true);

  //支持缩放按钮-前提是页面要支持才显示
  websettings.setbuiltinzoomcontrols(true);

  //设置客户端-不跳转到默认浏览器中
  webview.setwebviewclient(new webviewclient());

  //设置支持js调用java
  webview.addjavascriptinterface(new androidandjsinterface(), "android");

  //加载本地资源
//  webview.loadurl("http://atguigu.com/teacher.shtml");
  webview.loadurl("file:///android_asset/jscalljavacallphone.html");

 }

        3_加载jscalljavacallphone.html页面

//加载本地资源
// webview.loadurl("http://atguigu.com/teacher.shtml");
  webview.loadurl(file:///android_asset/jscalljavacallphone.html);

        4_从java代码传递json数据给javascript

class androidandjsinterface {
 /**
  * 该方法将被js调用,用于加载数据
  */
 @javascriptinterface
 public void showcontacts() {
  // 下面的代码建议在子线程中调用
  string json = "[{\"name\":\"阿福\", \"phone\":\"18600012345\"}]";
  // 调用js中的方法
  webview.loadurl("javascript:show('" + json + "')");
 }

 }

        5_拨打电话代码

class androidandjsinterface {
  /**
   * 该方法将被js调用,用于加载数据
   */
  @javascriptinterface
  public void showcontacts() {
   // 下面的代码建议在子线程中调用
   string json = "[{\"name\":\"阿福\", \"phone\":\"18600012345\"}]";
   // 调用js中的方法
   webview.loadurl("javascript:show('" + json + "')");
  }
  /**
   * 拨打电话
   * @param phone
   */
  public void call(string phone) {
   intent intent = new intent(intent.action_call, uri.parse("tel:" + phone));
//   startactivity(intent);
  }
 }

        6_h5页面:

<html>
 <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <title>insert title here</title>
  <script type="text/javascript">
   function show(jsondata){   
     var jsonobjs = eval(jsondata);
     var table = document.getelementbyid("persontable");
     for(var y=0; y<jsonobjs.length; y++){
      var tr = table.insertrow(table.rows.length); 
      var td1 = tr.insertcell(0);
      var td2 = tr.insertcell(1);
      td2.align = "center";
      td1.innerhtml = jsonobjs[y].name;
      td2.innerhtml = "<a href='javascript:android.call(\""+ jsonobjs[y].phone+ "\")'>"+ jsonobjs[y].phone+ "</a>";
     }
   }

  </script>
 </head>
 <body onload="javascript:android.showcontacts()">

 <table border="0" width="100%" id="persontable" cellspacing="0">
   <tr>
    <td width="30%">姓名</td>
    <td align="center">电话</td>
   </tr>
  </table>


 </body>
</html>

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!