转 【Android】- Android与html5交互操作
1. Android提供了WebView控件可访问网页
通过webView.loadUrl加载访问的页面,通过webView.getSettings()获得设置,设置WebView的属性和状态;
WebViewClient处理应用程序中自定义网页浏览程序,辅助webView通知、请求事件的。
2. WebView常用方法:
/*启用Javascript*/ webView.getSettings().setJavaScriptEnabled(true);
/*设置是否支持缩放*/ webView.getSettings().setBuiltInZoomControls(true);
/*设置不显示缩放的图标*/ webView.getSettings().setDisplayZoomControls(false);
/*设置支持聚焦*/ webView.getSettings().setSupportZoom(true);
/* 设置为使用webView推荐的窗口 */ webView.getSettings().setUseWideViewPort(true);
/* 设置网页自适应屏幕大小 */ webView.getSettings().setLoadWithOverviewMode(false);
/* HTML5的地理位置服务,设置为true,启用地理定位 */ webView.getSettings().setGeolocationEnabled(true);
/*不显示水平栏*/ webView.setHorizontalScrollBarEnabled(false); webView.setHorizontalFadingEdgeEnabled(false);
/*设置允许webView访问文件数据*/ webView.getSettings().setAllowFileAccess(true); /*是否显示网络图片*/ webView.getSettings().setBlockNetworkImage(true); /*设置缓冲模式*/ webView.getSettings().setCacheMode(); /*设置默认的字体大小*/ webView.getSettings().setDefaultFontSize();
/*设置在解码时使用的默认编码*/ webView.getSettings().setDefaultTextEncodingName(); /*设置固定使用的字体*/ webView.getSettings().setFixedFontFamily(); /*设置布局方式*/ webView.getSettings().setLayoutAlgorithm();
3.WebViewClient常用方法:
webView.setWebViewClient(new WebViewClient(){ /*控制新的连接在当前WebView中打开*/ @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { view.loadUrl(url); return super.shouldOverrideUrlLoading(view, request); } /*更新历史记录*/ @Override public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) { super.doUpdateVisitedHistory(view, url, isReload); } /*应用程序重新请求网页数据*/ @Override public void onFormResubmission(WebView view, Message dontResend, Message resend) { super.onFormResubmission(view, dontResend, resend); } /*加载指定地址提供的资源*/ @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); } /*网页加载完毕*/ @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } /*网页开始加载*/ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } /*报告错误信息*/ @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); } /*WebView发生改变*/ @Override public void onScaleChanged(WebView view, float oldScale, float newScale) { super.onScaleChanged(view, oldScale, newScale); } });
4.WebChromeClient常用方法:
webView.setWebChromeClient(new WebChromeClient(){ /*创建WebView*/ @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg); } /*关闭WebView*/ @Override public void onCloseWindow(WebView window) { super.onCloseWindow(window); } /*处理Javascript中的Alert对话框*/ @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { return super.onJsAlert(view, url, message, result); } /*处理Javascript中的Confirm对话框*/ @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { return super.onJsConfirm(view, url, message, result); } /*处理Javascript中的Prompt对话框*/ @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { return super.onJsPrompt(view, url, message, defaultValue, result); } /*加载进度条改变*/ @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); } /*网页图标更改*/ @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } /*网页Title更改*/ @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); } /*WebView显示焦点*/ @Override public void onRequestFocus(WebView view) { super.onRequestFocus(view); } });
5.实现网页内部逐级返回的方法
@Override public void onBackPressed() { if (webView.canGoBack()){ if (webView.getUrl().equals(url)){ super.onBackPressed(); }else{ webView.goBack(); } }else { super.onBackPressed(); } }
6.Android与html5交互
6.1 添加网络权限
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
6.2布局文件
<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.example.hxl.webview.WebActivity"> <WebView android:id="@id/webview" android:layout_width="match_parent" android:layout_height="match_parent"></WebView> </RelativeLayout>
6.3设置WebView支持javascript属性
webView.getSettings().setJavaScriptEnabled(true);
6.4加载html
若在assets中,以
private String url = "file:///android_asset/travel_app_h5/travelApp.html";
webView.loadUrl(url);
加载网络,以
private String url = "http://112.12.36.86:8008/travel_app/html/travel_app_h5/travelApp.html";
webView.loadUrl(url);
6.5android与html5交互
webView.addJavascriptInterface(this,"android");
需要在此调用的方法中加@JavascriptInterface增加安全性。
7. 实例 android调用html中的方法实现图片的移动和放大缩小
7.1 html代码:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Title</title> <style type="text/css" rel="stylesheet"> body{ padding: 0; margin: 0; } .app_range{ position: absolute; width: 100%; height: 100%; overflow: hidden; } #scenic_map{ margin-top: 0; margin-left: 0; height:100%; } </style> <script type="text/javascript" src="./js/jquery-3.0.0.min.js"></script> <script type="text/javascript"> function scale_map_blowUp() { var scenic_map_height = $("#scenic_map").height(); var blowUp_height = scenic_map_height*0.05+scenic_map_height; $("#scenic_map").css("height",blowUp_height+"px"); } function scale_map_reduce() { var scenic_map_height = $("#scenic_map").height(); var reduce_height = scenic_map_height-scenic_map_height*0.05; $("#scenic_map").css("height",reduce_height+"px"); } function move_top() { var scenic_map_magin_top = parseInt($("#scenic_map").css("marginTop")); var move_top_margin = scenic_map_magin_top-10; $("#scenic_map").css("marginTop",move_top_margin+"px"); } function move_bottom() { var scenic_map_magin_top = parseInt($("#scenic_map").css("marginTop")); var move_top_margin = scenic_map_magin_top+10; $("#scenic_map").css("marginTop",move_top_margin+"px"); } function move_left() { var scenic_map_magin_left = parseInt($("#scenic_map").css("marginLeft")); var move_left_margin = scenic_map_magin_left-10; $("#scenic_map").css("marginLeft",move_left_margin+"px"); } function move_right() { var scenic_map_magin_left = parseInt($("#scenic_map").css("marginLeft")); var move_left_margin = scenic_map_magin_left+10; $("#scenic_map").css("marginLeft",move_left_margin+"px"); } </script> </head> <body> <div id="app_range" class="app_range"> <img id="scenic_map" src="./images/ljds_map.jpg"> </div> </body> </html>
7.2 android代码
public class WebActivity extends AppCompatActivity implements View.OnTouchListener, ScaleGestureDetector.OnScaleGestureListener { //private String url = "http://112.12.36.86:8008/travel_app/html/travel_app_h5/travelApp.html"; private String url = "file:///android_asset/travel_app_h5/travelApp.html"; private WebView webView; private float lastX; private float lastY; /*是否移动了*/ private boolean isMoved; /*移动的阈值*/ private static final int TOUCH_SLOP = 50; private boolean isCanDrag; private int touchMove ; private ScaleGestureDetector scaleGestureDetector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web); initView(); initData(); setListener(); } private void setListener() { webView.setOnTouchListener(this); } @JavascriptInterface private void initData() { touchMove = ViewConfiguration.get(this).getScaledTouchSlop(); webView.loadUrl(url); webView.setWebViewClient(new WebViewClient(){ /*控制新的连接在当前WebView中打开*/ @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { view.loadUrl(url); return super.shouldOverrideUrlLoading(view, request); } }); /*启用Javascript*/ webView.getSettings().setJavaScriptEnabled(true); /*设置支持聚焦*/ webView.getSettings().setSupportZoom(true); /* 设置为使用webView推荐的窗口 */ webView.getSettings().setUseWideViewPort(true); /* 设置网页自适应屏幕大小 */ webView.getSettings().setLoadWithOverviewMode(false); webView.addJavascriptInterface(this,"android"); scaleGestureDetector = new ScaleGestureDetector(this,this); } private void initView() { webView = (WebView) findViewById(R.id.webview); } @Override public boolean onTouch(View view, MotionEvent motionEvent) { float x = motionEvent.getX(); float y = motionEvent.getY(); scaleGestureDetector.onTouchEvent(motionEvent); switch (motionEvent.getAction()){ case MotionEvent.ACTION_DOWN: isMoved = false; lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: if(isMoved) break; float dx = x - lastX; float dy = y - lastY; if(Math.abs(dx) > TOUCH_SLOP || Math.abs(dy) > TOUCH_SLOP) { //移动超过阈值,则表示移动了 isMoved = true; } if (!isCanDrag){ //判断是否移动 isCanDrag = isMove(dx,dy); } if (isCanDrag){ if (dy<0 &&Math.abs(dy)>Math.abs(dx)){ webView.loadUrl(String.format("javascript:move_top()")); }else if (dy>0 &&Math.abs(dy)>Math.abs(dx)){ webView.loadUrl(String.format("javascript:move_bottom()")); }else if(dx<0 &&Math.abs(dy)<Math.abs(dx)){ webView.loadUrl(String.format("javascript:move_left()")); }else if (dx>0 &&Math.abs(dy)<Math.abs(dx)){ webView.loadUrl(String.format("javascript:move_right()")); } } lastX = x; lastY = y; break; case MotionEvent.ACTION_UP: break; } return true; } private boolean isMove(float dx, float dy) { return Math.sqrt((dx*dx + dy*dy))>touchMove; } /** * 返回按钮按下 */ @Override public void onBackPressed() { if (webView.canGoBack()){ if (webView.getUrl().equals(url)){ super.onBackPressed(); }else{ webView.goBack(); } }else { super.onBackPressed(); } } /** * 缩放监听事件 */ @Override public boolean onScale(ScaleGestureDetector scaleGestureDetector) { //获得缩放系数值 // getScaleFactor()它的含义是 根据你的手势缩放程度预期得到的图片大小和当前图片大小的一个比值 // 放大时 > 1,缩小时 < 1 float scaleFactor = scaleGestureDetector.getScaleFactor(); if(scaleFactor<1){ webView.loadUrl(String.format("javascript:scale_map_reduce()")); }else { webView.loadUrl(String.format("javascript:scale_map_blowUp()")); } return true; } @Override public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) { return true; } @Override public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) { } }