在开发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了):



具体代码实现:

package com.xwj.webviewjstest;import android.annotation.SuppressLint;import android.app.Activity;import android.content.res.Configuration;import android.graphics.Bitmap;import android.os.Build;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.view.KeyEvent;import android.view.MotionEvent;import android.view.View;import android.webkit.JavascriptInterface;import android.webkit.WebSettings.PluginState;import android.webkit.WebView;import android.webkit.WebViewClient;import com.xwj.webviewjsdemo.R;@SuppressLint("SetJavaScriptEnabled")public class Test1Activity extends Activity {private WebView mWebView;private static final String URL = "http://bbs.66u.com";// 用于记录出错页面的url 方便重新加载private String mFailingUrl = null;/*private Handler handler = new Handler(){  //对应方法3@Overridepublic void handleMessage(Message msg) {if (msg.what == 1) {if (mFailingUrl != null) {mWebView.loadUrl(mFailingUrl);}}super.handleMessage(msg);}};*/private Handler handler1 = new Handler();public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_test1);mWebView = (WebView) findViewById(R.id.wv_test1);initWebViewSettings();initWebview();}private void initWebViewSettings() {mWebView.setWebViewClient(new MyWebViewClient());mWebView.setOnTouchListener(new View.OnTouchListener() {@Overridepublic boolean onTouch(View v, MotionEvent event) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:case MotionEvent.ACTION_UP:if (!v.hasFocus()) {v.requestFocus();v.requestFocusFromTouch();}break;}return false;}});// 启用JavaScriptmWebView.getSettings().setJavaScriptEnabled(true);mWebView.getSettings().setSupportZoom(true);mWebView.getSettings().setUseWideViewPort(true);mWebView.getSettings().setLoadWithOverviewMode(true);mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);if (Build.VERSION.SDK_INT < 19) {if (Build.VERSION.SDK_INT >8) {        mWebView.getSettings().setPluginState(PluginState.ON);        } }}private void initWebview() {mWebView.addJavascriptInterface(new JsInterface(), "jsinterface");mWebView.loadUrl(URL);}class MyWebViewClient extends WebViewClient {@Overridepublic boolean shouldOverrideUrlLoading(WebView view, String url) {// 在webview加载下一页,而不会打开浏览器view.loadUrl(url);return true;}@Overridepublic void onPageStarted(WebView view, String url, Bitmap favicon) {super.onPageStarted(view, url, favicon);}@Overridepublic void onPageFinished(WebView view, String url) {super.onPageFinished(view, url);}@Overridepublic void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {super.onReceivedError(view, errorCode, description, failingUrl);mFailingUrl = failingUrl;//加载出错的自定义界面view.loadUrl("file:///android_asset/error.html");}}class JsInterface {@JavascriptInterfacepublic void errorReload() {//方法1/*new Handler().post(new Runnable() {  //此方法最好不用,因为在webview中最好不要在工作线程中声明handler@Overridepublic void run() {if (mFailingUrl != null) {mWebView.loadUrl(mFailingUrl);}}});可将方法1修改成如下:Returns the application's main looper, which lives in the main thread of the application.参考blog:http://blog.csdn.net/mylzc/article/details/6771331*/new Handler(Looper.getMainLooper()).post(new Runnable() {@Overridepublic void run() {if (mFailingUrl != null) {mWebView.loadUrl(mFailingUrl);}}});/*//方法2handler1.post(new Runnable() {@Overridepublic void run() {if (mFailingUrl != null) { //当点击出错界面的按钮时,重新加载mWebView.loadUrl(mFailingUrl);}}});*///方法3/*new Thread(){public void run() {Message msg = Message.obtain();msg.what = 1;handler.sendMessage(msg);};}.start();*///方法4/* * runOnUiThread(new Runnable() {public void run() {if (mFailingUrl != null) {mWebView.loadUrl(mFailingUrl);}}});*/}}@Overridepublic void onConfigurationChanged(Configuration newConfig) {super.onConfigurationChanged(newConfig);}public void onResume() {super.onResume();if (mWebView != null) {mWebView.onResume();mWebView.resumeTimers();}}@Overridepublic void onPause() {if (mWebView != null) {mWebView.onPause();mWebView.pauseTimers();}super.onPause();}@Overridepublic boolean onKeyDown(int keyCode, KeyEvent event) {// 返回键监听 点击返回如果有上一页面不会马上退出if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {mWebView.goBack();return true;}return super.onKeyDown(keyCode, event);}}

html端代码:

<!doctype html><html><head><meta charset="utf-8"><title>无标题文档</title>        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />        <meta content="yes" name="apple-mobile-web-app-capable">        <meta content="yes" name="apple-touch-fullscreen">        <meta content="telephone=no" name="format-detection">        <meta content="black" name="apple-mobile-web-app-status-bar-style">        <style type="text/css">        *{margin:0;padding:0;}body{color: #928B8B;min-width:320px;text-align:center;font-family:'Microsoft YaHei';}.content{background:#f8f8f8;overflow:hidden;width:100%;position:relative;}.mainbody{width:100%;position:absolute;top:50%;margin-top:-100px;}.mainbody img{width:80px;height:80px;}.mainbody p{width:100%;display:block;text-align:center;font-size:24px;margin:15px 0;}.try{width:100px;text-align:center;padding:6px 0;border-style:none;color:#928B8B;border:1px solid #F0EBEB;background:#fff;font-size:16px;}.try:hover{background:#f2f2f2;}        </style></head>    <body><div class="content" id="id">        <div class="mainbody">            <img src="img/error_icon.png" />            <p id="id_wei">网络异常,请检查网络连接</p>                <button id="btn" class="try" onClick="window.jsinterface.errorReload()">再试一次</button>            </div>        </div>                <script type="text/javascript">var a = document.documentElement.clientHeight;document.getElementById("id").style.height = a+"px";</script>     </body></html>


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

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

例2、


例3、


例4、运用过程4

效果图:


java代码:

package com.xwj.webviewjstest;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.webkit.WebView;import android.widget.Button;import com.xwj.webviewjsdemo.R;public class Test2Activity extends Activity {private WebView mWebView;private Button mBtn;private static final String URL = "file:///android_asset/test2.html";private static final String NAME = "HELLO";public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_test2);mWebView = (WebView) findViewById(R.id.wv_test2);mBtn = (Button) findViewById(R.id.btn_test2);initWebViewSettings();initWebview();}private void initWebViewSettings() {// 启用JavaScriptmWebView.getSettings().setJavaScriptEnabled(true);mWebView.getSettings().setSupportZoom(true);mWebView.getSettings().setUseWideViewPort(true);mWebView.getSettings().setLoadWithOverviewMode(true);mWebView.getSettings().setDefaultTextEncodingName("utf-8");mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);}private void initWebview() {mWebView.loadUrl(URL);mBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 注:传的参数NAME一定要加'',否则不能调用mWebView.loadUrl("javascript:sayhello(" + "'" + NAME + "')");}});}public void onResume() {super.onResume();if (mWebView != null) {mWebView.onResume();mWebView.resumeTimers();}}@Overridepublic void onPause() {if (mWebView != null) {mWebView.onPause();mWebView.pauseTimers();}super.onPause();}}

html代码:

<html>  <head>  <meta http-equiv="Content-Type"  content="text/html;charset=gb2312">   <style type="text/css">        *{margin:0;padding:0;}body{color: #928B8B;min-width:320px;text-align:center;font-family:'Microsoft YaHei';font-size:42px;}</style><script type="text/javascript">  function sayhello(namejs){       document.getElementById("content").innerHTML +=              ("<br\>java调用js函数--参数为:"+namejs);  }  </script>  </head>  <body>  Love me and love you<br/>  <br/>  <div id="content">显示内如:</div>  </body>  </html> 

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


欢迎大家总结补充,谢谢

转载请标明出处(http://blog.csdn.net/wei18359100306/article/details/42468739),谢谢!



更多相关文章

  1. 东拼西凑写的android 相机例子,包含一些遇到的坑
  2. Android(安卓)值得深入思考的几个面试问答分享
  3. Android(安卓)数据持久化(SQLite数据存储)
  4. Android线程与并行,AsyncTask(AsyncTask回调方法、AsyncTask泛型参
  5. android 短信接收流程分析——为更好的拦截短信做准备
  6. Anroid Wear OS 手表应用开发 - 微光模式 AmbientMode
  7. APP如何推广?策划APP推广方案的好方法
  8. 键盘按下和抬起事件(keydown,keyup)——原创
  9. Android中直播视频技术探究之---摄像头Camera视频源数据采集解析

随机推荐

  1. GNOME Mutter的代码清理工作将促进支持Vu
  2. 又说骚话,Linus再次拒绝Intel CPU漏洞补丁
  3. 不出意外的话,Go泛型终于要引入了
  4. .NET IDE Rider公布2020.2路线图
  5. Chrome团队:2020年了,浏览器兼容性还是一个
  6. 除了域名,Chrome或将隐藏整个URL
  7. 猎鹰与龙飞船基于Linux,采用C++、Chromium
  8. Windows任务管理器远比想象中的复杂
  9. antirez辞去Redis项目领导者职务
  10. 源码解析容器底层cgroup的实现