在开发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
-
@Override
-
public 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() {
-
@Override
-
public 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;
-
}
-
});
-
// 启用JavaScript
-
mWebView.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 {
-
@Override
-
public boolean shouldOverrideUrlLoading(WebView view, String url) {
-
// 在webview加载下一页,而不会打开浏览器
-
view.loadUrl(url);
-
return true;
-
}
-
@Override
-
public void onPageStarted(WebView view, String url, Bitmap favicon) {
-
super.onPageStarted(view, url, favicon);
-
}
-
@Override
-
public void onPageFinished(WebView view, String url) {
-
super.onPageFinished(view, url);
-
}
-
@Override
-
public 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 {
-
@JavascriptInterface
-
public void errorReload() {
-
//方法1
-
/*new Handler().post(new Runnable() { //此方法最好不用,因为在webview中最好不要在工作线程中声明handler
-
@Override
-
public 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.youkuaiyun.com/mylzc/article/details/6771331
-
*/
-
new Handler(Looper.getMainLooper()).post(new Runnable() {
-
@Override
-
public void run() {
-
if (mFailingUrl != null) {
-
mWebView.loadUrl(mFailingUrl);
-
}
-
}
-
});
-
/*//方法2
-
handler1.post(new Runnable() {
-
@Override
-
public 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);
-
}
-
}
-
});*/
-
}
-
}
-
@Override
-
public void onConfigurationChanged(Configuration newConfig) {
-
super.onConfigurationChanged(newConfig);
-
}
-
public void onResume() {
-
super.onResume();
-
if (mWebView != null) {
-
mWebView.onResume();
-
mWebView.resumeTimers();
-
}
-
}
-
@Override
-
public void onPause() {
-
if (mWebView != null) {
-
mWebView.onPause();
-
mWebView.pauseTimers();
-
}
-
super.onPause();
-
}
-
@Override
-
public 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() {
-
// 启用JavaScript
-
mWebView.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() {
-
@Override
-
public void onClick(View v) {
-
// 注:传的参数NAME一定要加'',否则不能调用
-
mWebView.loadUrl("javascript:sayhello(" + "'" + NAME + "')");
-
}
-
});
-
}
-
public void onResume() {
-
super.onResume();
-
if (mWebView != null) {
-
mWebView.onResume();
-
mWebView.resumeTimers();
-
}
-
}
-
@Override
-
public 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类型,参数一定要有单引号,多个参数则自己拼接)