webView与js的交互以及传参

在开发android webview的过程中经常会碰到这样的需求

1、点击webview上的数字手机跳到电话页面或自动播打电话

2、无网络出错,出现自定义本地出错页面,点击页面按钮重新加载

3、点击页面的某段话,自动发送短信

4、点击图片能放大显示

、、、

 

要完成上面的功能,基本上都要涉及webview 和 js 的交互,下面简单举几个小例子

涉及的过程:

1、html的js脚本调用本地android中的java方法-->无参

2、android中的java代码调用html的js脚本-->无参

3、html的js脚本调用本地android中的java方法-->有参

4、android中的java代码调用html的js脚本-->有参

 

例1、自定义本地出错页面,点击页面按钮重新加载(使用过程1)

效果图(本人比较懒,就不搞gif了):

  

 

具体代码实现:

 

 
  1. package com.xwj.webviewjstest;

  2.  
  3. import android.annotation.SuppressLint;

  4. import android.app.Activity;

  5. import android.content.res.Configuration;

  6. import android.graphics.Bitmap;

  7. import android.os.Build;

  8. import android.os.Bundle;

  9. import android.os.Handler;

  10. import android.os.Looper;

  11. import android.view.KeyEvent;

  12. import android.view.MotionEvent;

  13. import android.view.View;

  14. import android.webkit.JavascriptInterface;

  15. import android.webkit.WebSettings.PluginState;

  16. import android.webkit.WebView;

  17. import android.webkit.WebViewClient;

  18.  
  19. import com.xwj.webviewjsdemo.R;

  20.  
  21. @SuppressLint("SetJavaScriptEnabled")

  22. public class Test1Activity extends Activity {

  23. private WebView mWebView;

  24. private static final String URL = "http://bbs.66u.com";

  25. // 用于记录出错页面的url 方便重新加载

  26. private String mFailingUrl = null;

  27. /*private Handler handler = new Handler(){ //对应方法3

  28. @Override

  29. public void handleMessage(Message msg) {

  30. if (msg.what == 1) {

  31. if (mFailingUrl != null) {

  32. mWebView.loadUrl(mFailingUrl);

  33. }

  34. }

  35. super.handleMessage(msg);

  36. }

  37. };*/

  38. private Handler handler1 = new Handler();

  39.  
  40. public void onCreate(Bundle savedInstanceState) {

  41. super.onCreate(savedInstanceState);

  42. setContentView(R.layout.activity_test1);

  43. mWebView = (WebView) findViewById(R.id.wv_test1);

  44. initWebViewSettings();

  45. initWebview();

  46. }

  47.  
  48. private void initWebViewSettings() {

  49. mWebView.setWebViewClient(new MyWebViewClient());

  50. mWebView.setOnTouchListener(new View.OnTouchListener() {

  51. @Override

  52. public boolean onTouch(View v, MotionEvent event) {

  53. switch (event.getAction()) {

  54. case MotionEvent.ACTION_DOWN:

  55. case MotionEvent.ACTION_UP:

  56. if (!v.hasFocus()) {

  57. v.requestFocus();

  58. v.requestFocusFromTouch();

  59. }

  60. break;

  61. }

  62. return false;

  63. }

  64. });

  65. // 启用JavaScript

  66. mWebView.getSettings().setJavaScriptEnabled(true);

  67. mWebView.getSettings().setSupportZoom(true);

  68. mWebView.getSettings().setUseWideViewPort(true);

  69. mWebView.getSettings().setLoadWithOverviewMode(true);

  70. mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

  71.  
  72. if (Build.VERSION.SDK_INT < 19) {

  73. if (Build.VERSION.SDK_INT >8) {

  74. mWebView.getSettings().setPluginState(PluginState.ON);

  75. }

  76. }

  77. }

  78.  
  79. private void initWebview() {

  80. mWebView.addJavascriptInterface(new JsInterface(), "jsinterface");

  81. mWebView.loadUrl(URL);

  82. }

  83.  
  84. class MyWebViewClient extends WebViewClient {

  85. @Override

  86. public boolean shouldOverrideUrlLoading(WebView view, String url) {

  87. // 在webview加载下一页,而不会打开浏览器

  88. view.loadUrl(url);

  89. return true;

  90. }

  91.  
  92. @Override

  93. public void onPageStarted(WebView view, String url, Bitmap favicon) {

  94. super.onPageStarted(view, url, favicon);

  95. }

  96.  
  97. @Override

  98. public void onPageFinished(WebView view, String url) {

  99. super.onPageFinished(view, url);

  100. }

  101.  
  102. @Override

  103. public void onReceivedError(WebView view, int errorCode,

  104. String description, String failingUrl) {

  105. super.onReceivedError(view, errorCode, description, failingUrl);

  106. mFailingUrl = failingUrl;

  107. //加载出错的自定义界面

  108. view.loadUrl("file:///android_asset/error.html");

  109. }

  110. }

  111.  
  112. class JsInterface {

  113. @JavascriptInterface

  114. public void errorReload() {

  115. //方法1

  116. /*new Handler().post(new Runnable() { //此方法最好不用,因为在webview中最好不要在工作线程中声明handler

  117.  
  118. @Override

  119. public void run() {

  120. if (mFailingUrl != null) {

  121. mWebView.loadUrl(mFailingUrl);

  122. }

  123. }

  124. });

  125.  
  126. 可将方法1修改成如下:Returns the application's main looper, which lives in the main thread of the application.

  127. 参考blog:http://blog.csdn.net/mylzc/article/details/6771331

  128. */

  129.  
  130. new Handler(Looper.getMainLooper()).post(new Runnable() {

  131.  
  132. @Override

  133. public void run() {

  134. if (mFailingUrl != null) {

  135. mWebView.loadUrl(mFailingUrl);

  136. }

  137. }

  138. });

  139.  
  140. /*//方法2

  141. handler1.post(new Runnable() {

  142.  
  143. @Override

  144. public void run() {

  145. if (mFailingUrl != null) {

  146. //当点击出错界面的按钮时,重新加载

  147. mWebView.loadUrl(mFailingUrl);

  148. }

  149. }

  150. });*/

  151. //方法3

  152. /*new Thread(){

  153. public void run() {

  154. Message msg = Message.obtain();

  155. msg.what = 1;

  156. handler.sendMessage(msg);

  157. };

  158. }.start();*/

  159. //方法4

  160. /*

  161. * runOnUiThread(new Runnable() {

  162. public void run() {

  163. if (mFailingUrl != null) {

  164. mWebView.loadUrl(mFailingUrl);

  165. }

  166. }

  167. });*/

  168. }

  169. }

  170.  
  171. @Override

  172. public void onConfigurationChanged(Configuration newConfig) {

  173. super.onConfigurationChanged(newConfig);

  174. }

  175.  
  176. public void onResume() {

  177. super.onResume();

  178. if (mWebView != null) {

  179. mWebView.onResume();

  180. mWebView.resumeTimers();

  181. }

  182. }

  183.  
  184. @Override

  185. public void onPause() {

  186. if (mWebView != null) {

  187. mWebView.onPause();

  188. mWebView.pauseTimers();

  189. }

  190. super.onPause();

  191. }

  192.  
  193. @Override

  194. public boolean onKeyDown(int keyCode, KeyEvent event) {

  195. // 返回键监听 点击返回如果有上一页面不会马上退出

  196. if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {

  197. mWebView.goBack();

  198. return true;

  199. }

  200. return super.onKeyDown(keyCode, event);

  201. }

  202. }


html端代码:

 

 

 
  1. <!doctype html>

  2. <html>

  3. <head>

  4. <meta charset="utf-8">

  5. <title>无标题文档</title>

  6. <meta name="viewport" content= "width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />

  7. <meta content="yes" name="apple-mobile-web-app-capable">

  8. <meta content="yes" name="apple-touch-fullscreen">

  9. <meta content="telephone=no" name="format-detection">

  10. <meta content="black" name="apple-mobile-web-app-status-bar-style">

  11. <style type="text/css">

  12. *{

  13. margin:0;

  14. padding:0;

  15. }

  16.  
  17. body{

  18. color: #928B8B;

  19. min-width:320px;

  20. text-align:center;

  21. font-family:'Microsoft YaHei';

  22. }

  23.  
  24. .content{

  25. background:#f8f8f8;

  26. overflow:hidden;

  27. width:100%;

  28. position:relative;

  29. }

  30.  
  31. .mainbody{

  32. width:100%;

  33. position:absolute;

  34. top:50%;

  35. margin-top:-100px;

  36. }

  37.  
  38. .mainbody img{

  39. width:80px;

  40. height:80px;

  41. }

  42.  
  43. .mainbody p{

  44. width:100%;

  45. display:block;

  46. text-align:center;

  47. font-size:24px;

  48. margin:15px 0;

  49. }

  50.  
  51. .try{

  52. width:100px;

  53. text-align:center;

  54. padding:6px 0;

  55. border-style:none;

  56. color:#928B8B;

  57. border:1px solid #F0EBEB;

  58. background:#fff;

  59. font-size:16px;

  60. }

  61.  
  62. .try:hover{

  63. background:#f2f2f2;

  64. }

  65. </style>

  66. </head>

  67.  
  68.  
  69. <body>

  70. <div class="content" id="id">

  71. <div class="mainbody">

  72. <img src="img/error_icon.png" />

  73. <p id="id_wei">网络异常,请检查网络连接</p>

  74. <button id="btn" class="try" onClick="window.jsinterface.errorReload()">再试一次</button>

  75. </div>

  76. </div>

  77.  
  78. <script type="text/javascript">

  79. var a = document.documentElement.clientHeight;

  80. document.getElementById("id").style.height = a+"px";

  81. </script>

  82.  
  83.  
  84. </body>

  85. </html>

 

 

onClick="window.jsinterface.errorReload()"
mWebView.addJavascriptInterface(new JsInterface(), "jsinterface");


通过webview绑定javascriptInterface,js脚本通过这个接口(jsinterface)来调用java代码 
 

例2、

 

例3、

 

例4、运用过程4

效果图:

java代码:

 

 
  1. package com.xwj.webviewjstest;

  2.  
  3. import android.app.Activity;

  4. import android.os.Bundle;

  5. import android.view.View;

  6. import android.view.View.OnClickListener;

  7. import android.webkit.WebView;

  8. import android.widget.Button;

  9.  
  10. import com.xwj.webviewjsdemo.R;

  11.  
  12. public class Test2Activity extends Activity {

  13. private WebView mWebView;

  14. private Button mBtn;

  15. private static final String URL = "file:///android_asset/test2.html";

  16. private static final String NAME = "HELLO";

  17.  
  18. public void onCreate(Bundle savedInstanceState) {

  19. super.onCreate(savedInstanceState);

  20. setContentView(R.layout.activity_test2);

  21. mWebView = (WebView) findViewById(R.id.wv_test2);

  22. mBtn = (Button) findViewById(R.id.btn_test2);

  23. initWebViewSettings();

  24. initWebview();

  25. }

  26.  
  27. private void initWebViewSettings() {

  28. // 启用JavaScript

  29. mWebView.getSettings().setJavaScriptEnabled(true);

  30. mWebView.getSettings().setSupportZoom(true);

  31. mWebView.getSettings().setUseWideViewPort(true);

  32. mWebView.getSettings().setLoadWithOverviewMode(true);

  33. mWebView.getSettings().setDefaultTextEncodingName("utf-8");

  34. mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

  35. }

  36.  
  37. private void initWebview() {

  38. mWebView.loadUrl(URL);

  39. mBtn.setOnClickListener(new OnClickListener() {

  40.  
  41. @Override

  42. public void onClick(View v) {

  43. // 注:传的参数NAME一定要加'',否则不能调用

  44. mWebView.loadUrl("javascript:sayhello(" + "'" + NAME + "')");

  45. }

  46. });

  47. }

  48.  
  49. public void onResume() {

  50. super.onResume();

  51. if (mWebView != null) {

  52. mWebView.onResume();

  53. mWebView.resumeTimers();

  54. }

  55. }

  56.  
  57. @Override

  58. public void onPause() {

  59. if (mWebView != null) {

  60. mWebView.onPause();

  61. mWebView.pauseTimers();

  62. }

  63. super.onPause();

  64. }

  65. }


html代码:

 

 

 
  1. <html>

  2. <head>

  3. <meta http-equiv="Content-Type" content="text/html;charset=gb2312">

  4. <style type="text/css">

  5. *{

  6. margin:0;

  7. padding:0;

  8. }

  9.  
  10. body{

  11. color: #928B8B;

  12. min-width:320px;

  13. text-align:center;

  14. font-family:'Microsoft YaHei';

  15. font-size:42px;

  16. }

  17. </style>

  18. <script type="text/javascript">

  19. function sayhello(namejs){

  20. document.getElementById("content").innerHTML +=

  21. ("<br\>java调用js函数--参数为:"+namejs);

  22. }

  23. </script>

  24. </head>

  25. <body>

  26. Love me and love you<br/>

  27. <br/>

  28. <div id="content">显示内如:</div>

  29. </body>

  30. </html>


注:参数类型要注意(如果为String类型,参数一定要有单引号,多个参数则自己拼接)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值