Android与Javascript交互之入门

本文介绍了Android使用WebView与JavaScript交互的入门知识,包括关键类WebChromeClient和WebViewClient的使用,以及如何注入Java对象到JavaScript上下文。示例代码演示了Android调用JavaScript方法和JavaScript调用Android方法的过程。
摘要由CSDN通过智能技术生成

AndroidJavaScript交互主要是使用的WebView。

关于WebView,一般涉及到2个类:WebChromeClient 和 WebViewClient 。

开发的大致流程为(摘自Android developer):

A WebView has several customization points where you can add your own behavior. These are:

Creating and setting a WebChromeClient subclass. This class is called when something that might impact a browser UI happens, for instance, progress updates and JavaScript alerts are sent here (see Debugging Tasks).
Creating and setting a WebViewClient subclass. It will be called when things happen that impact the rendering of the content, eg, errors or form submissions. You can also intercept URL loading here (via shouldOverrideUrlLoading()).
Modifying the WebSettings, such as enabling JavaScript with setJavaScriptEnabled().

Injecting Java objects into the WebView using the addJavascriptInterface(Object, String) method. This method allows you to inject Java objects into a page's JavaScript context, so that they can be accessed by JavaScript in the page.

好了,废话不多说,上Demo。

此demo完成了Android与Javascript交互的基础功能,并用json字符串进行了值传递。

秉持一贯的风格,知识内容都在代码注释中,这样方便以后复习。(布局就不贴了,比较简单)

整个工程结构比较简单:



首先是这个jsdroid.html文件的界面(贴界面其实有点2 --!):


html代码比较简单:

[html]  view plain   copy
  print ?
  1. <html>  
  2. <meta charset="GBK">  
  3. <head>  
  4. <title>js交互android</title>  
  5. <script type="text/javascript">  
  6.       
  7.     function show(){  
  8.     var a = document.getElementById("text").value;  
  9.     alert("警告,你输入的是:"+a);  
  10.     }  
  11.   
  12.     function rfInfo(jsonStr) {   
  13.             document.getElementById("info").innerHTML="从Android客户端传来的作者信息:"+jsonStr.Developer;   
  14.         }   
  15.   
  16.     function cfm() {   
  17.     if(confirm("确认界面提示?")){  
  18.     return true;  
  19.     }else  
  20.      return false;  
  21.     }   
  22.   
  23.     function pmt() {   
  24.     var place = prompt("请输入位置?","");  
  25.     }  
  26.   
  27. </script>  
  28. </head>  
  29. <body>  
  30. <form action="">  
  31.     <p><div id="info" >从Android客户端传来的作者信息:</div></p>  
  32.     <p><input type="text" id="text" value="input your msg"/></p>  
  33.     <p><div id="inputinfo" >输入的信息:</div></p>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值