【Android】WebView加载html与JS交互

一、加载Html的几种方法

  1. 直接在Activity中实例化WebView

    WebView webview =new WebView(this);
    webview.loadUrl(…);

  2. 在XML中生命webview
    WebView webView = (WebView) findViewById(R.id.webview);

  3. 载入工程内部页面 page.html存储在工程文件的assets根目录下

     webView = (WebView) findViewById(R.id.webview);  
     webView.loadUrl("file:///file:///android_asset/page.html"); 
    

二、加载页面时几种简单API使用

  • 设置缩放

       mWebView.getSettings().setBuiltInZoomControls(true); 
    
  • 在webview添加对js的支持

      setting.setJavaScriptEnabled(true);//支持js
    
  • 添加对中文支持

      setting.setDefaultTextEncodingName("GBK");//设置字符编码  
    
  • 设置页面滚动条风格

      webView.setScrollBarStyle(0);//滚动条风格,为0指滚动条不占用空间,直接覆盖在网页上
    
      取消滚动条
          this.setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
    
  • listview,webview中滚动拖动到顶部或者底部时的阴影(滑动到项部或底部不固定)

       WebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    

三、浏览器优化操作处理:

  1. WebView默认用系统自带浏览器处理页面跳转。为了让页面跳转在当前WebView中进行,

    重写WebViewClient

    mWebView.setWebViewClient(new WebViewClient() {  
        @Override  
        public boolean shouldOverrideUrlLoading(WebView view, String url) {  
            view.loadUrl(url);//使用当前WebView处理跳转  
            return true;//true表示此事件在此处被处理,不需要再广播  
        }  
        @Override  
        public void onPageStarted(WebView view, String url, Bitmap favicon) {  
            //有页面跳转时被回调  
        }  
        @Override  
        public void onPageFinished(WebView view, String url) {  
            //页面跳转结束后被回调  
        }  
        @Override  
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {  
            Toast.makeText(WebViewDemo.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();  
        }  
    }); 
    
  2. 当WebView内容影响UI时调用WebChromeClient的方法

     mWebView.setWebChromeClient(new WebChromeClient() {  
        /** 
         * 处理JavaScript Alert事件 
         */  
        @Override  
        public boolean onJsAlert(WebView view, String url,  
                String message, final JsResult result) {  
            //用Android组件替换  
            new AlertDialog.Builder(WebViewDemo.this)  
                .setTitle("JS提示")  
                .setMessage(message)  
                .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int which) {  
                        result.confirm();  
                    }  
                })  
                .setCancelable(false)  
                .create().show();  
            return true;  
        }  
    });   
    
  3. 按BACK键时,不会返回跳转前的页面,而是退出本Activity,重写onKeyDown()方法来解决此问题

     @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        //处理WebView跳转返回  
        if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {  
            mWebView.goBack();  
            return true;  
        }  
        return super.onKeyDown(keyCode, event);  
    }  
      
    private class JsToJava {  
        public void jsMethod(String paramFromJS) {  
            Log.i("CDH", paramFromJS);  
        }  
    } 
    

四、WebView与JS交互

  • 总纲

      	 /* 
                            绑定Java对象到WebView,这样可以让JS与Java通信(JS访问Java方法) 
                            第一个参数是自定义类对象,映射成JS对象 
                            第二个参数是第一个参数的JS别名 
                            调用示例: 
              mWebView.loadUrl("javascript:window.stub.jsMethod('param')"); 
           */  
          mWebView.addJavascriptInterface(new JsToJava(), "stub");  
            
          final EditText mEditText = (EditText)findViewById(R.id.web_view_text);  
    
          findViewById(R.id.web_view_search).setOnClickListener(new OnClickListener() {  
              @Override  
              public void onClick(View view) {  
                  String url = mEditText.getText().toString();  
                  if (url == null || "".equals(url)) {  
                      Toast.makeText(WebViewDemo.this, "请输入URL", Toast.LENGTH_SHORT).show();  
                  } else {  
                      if (!url.startsWith("http:") && !url.startsWith("file:")) {  
                          url = "http://" + url;  
                      }  
                      mWebView.loadUrl(url);  
                  }  
              }  
          });  
          //默认页面  
          mWebView.loadUrl("file:///android_asset/js_interact_demo.html");  
      }  
    
  • 扑捉加载页面JS的过程

    • 注意到webview提供的两个方法:

    • setWebChromeClient方法正是可以处理progress的加载,此外,还可以处理js对话框,在webview中显示icon图标等。

    • 对于setWebViewClient方法,一般用来处理html的加载(需要重载onPageStarted(WebView view, String url, Bitmap favicon))、关闭(需要重载onPageFinished(WebViewview, String url)方法)。

        webView.setWebChromeClient(new WebChromeClient() {
        	public void onProgressChanged(WebView view, int progress) {// 载入进度改变而触发
        			if (progress == 100) {
        					handler.sendEmptyMessage(1);// 如果全部载入,隐藏进度对话框
        			}
        				super.onProgressChanged(view, progress);
        		}
        });
      
  • 获取java中的数据:单独构建一个接口,作为处理js与java的数据交互的桥梁

      封装的代码AndroidToastForJs.java
      
      public class AndroidToastForJs {
      		
      		private Context mContext;
      	
      	public AndroidToastForJs(Context context){
      			this.mContext = context;
      		}
      		
      	//webview中调用toast原生组件
      	public void showToast(String toast) {
      			Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
      		}
      		
      	//webview中求和
      	public int sum(int a,int b){
      			return a+b;
      		}
      		
      	 //以json实现webview与js之间的数据交互
      	public String jsontohtml(){
      			JSONObject map;
      			JSONArray array = new JSONArray();
      			try {
      				map = new JSONObject();
      				map.put("name","aaron");
      				map.put("age", 25);
      				map.put("address", "中国上海");
      				array.put(map);
      				
      				map = new JSONObject();
      				map.put("name","jacky");
      				map.put("age", 22);
      				map.put("address", "中国北京");
      				array.put(map);
      				
      				map = new JSONObject();
      				map.put("name","vans");
      				map.put("age", 26);
      				map.put("address", "中国深圳");
      				map.put("phone","13888888888");
      				array.put(map);
      			} catch (JSONException e) {
      				e.printStackTrace();
      			}
      			return array.toString();
      		}
      	}
    

Webview提供的传入js的方法:

webView.addJavascriptInterface(new AndroidToastForJs(mContext), "JavaScriptInterface");

Html页面jsonData.html设计的部分代码如下

	<script type="text/javascript">
		var result = JavaScriptInterface.jsontohtml();
		var obj = eval("("+result+")");//解析json字符串
		function showAndroidToast(toast) 
		{        
			JavaScriptInterface.showToast(toast); 
	    }
		function getjsonData(){
			var result = JavaScriptInterface.jsontohtml();
			var obj = eval("("+result+")");//解析json字符串
			for(i=0;i<obj.length;i++){
				var user=obj[i];
				document.write("<p>姓名:"+user.name+"</p>");
				document.write("<p>年龄:"+user.age+"</p>");
				document.write("<p>地址:"+user.address+"</p>");
				if(user.phone!=null){
					document.write("<p>手机号码:"+user.address+"</p>");
				}
			}
		}	
		function list(){
			document.write("<div data-role='header'><p>another</p></div>");
		}
		</script>
	</head> 
	<body> 
	<div data-role="page" >
		<div data-role="header" data-theme="c">
			<h1>Android via Interface</h1>
		</div><!-- /header -->
		<div data-role="content">	
			<button value="say hello" onclick="showAndroidToast('Hello,Android!')" data-theme="e"></button>
			<button value="get json data" onclick="getjsonData()" data-theme="e"></button>	
		</div><!-- /content -->
	<div data-role="collapsible" data-theme="c" data-content-theme="f">
	   <h3>I'm <script>document.write(obj[0].name);</script>,click to see my info</h3>
	   <p><script>document.write("<p>姓名:"+obj[0].name+"</p>");</script></p>
	   <p><script>document.write("<p>年龄:"+obj[0].age+"</p>");</script></p>
	   <p><script>document.write("<p>地址:"+obj[0].address+"</p>");</script></p>
	</div>
		<div data-role="footer" data-theme="c">
			<h4>Page Footer</h4>
		</div><!-- /footer -->
	</div><!-- /page -->
	</body>

问题解决:

  1. 多图片网页手机加载数度慢

     1. 建议先用 webView.getSettings().setBlockNetworkImage(true); 将图片下载阻塞
     2. 在浏览器的OnPageFinished事件中设置 webView.getSettings().setBlockNetworkImage(false); 
     	通过图片的延迟载入,让网页能更快地显示
    

HTML5交互:

HTML5本地存储在Android中的应用

  • HTML5提供了2种客户端存储数据新方法:

    1. localStorage 没有时间限制

    2. sessionStorage 针对一个Session的数据存储

       <script type="text/javascript"> 
       	localStorage.lastname="Smith"; 
       	document.write(localStorage.lastname); 
       </script> 
       <script type="text/javascript"> 
       	sessionStorage.lastname="Smith"; 
       	document.write(sessionStorage.lastname);
       </script> 
      

WebStorage的API:

//清空storage
localStorage.clear();

//设置一个键值
localStorage.setItem(“yarin”,“yangfegnsheng”);

//获取一个键值
localStorage.getItem(“yarin”); 

//获取指定下标的键的名称(如同Array)
localStorage.key(0); 

//return “fresh” //删除一个键值
localStorage.removeItem(“yarin”);

注意一定要在设置中开启哦
setDomStorageEnabled(true)

在Android中进行操作:

//启用数据库
webSettings.setDatabaseEnabled(true);  
String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
//设置数据库路径
webSettings.setDatabasePath(dir);
//使用localStorage则必须打开
webSettings.setDomStorageEnabled(true);
//扩充数据库的容量(在WebChromeClinet中实现)
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, 
		long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
	quotaUpdater.updateQuota(estimatedSize * 2);
}	

在JS中按常规进行数据库操作:

tHandler, errorHandler);
		}
	);	
}
function dataSelectHandler(transaction, results){
	// Handle the results
	for (var i=0; i<results.rows.length; i++) {
		var row = results.rows.item(i);
		var newFeature = new Object();
		newFeature.name   = row['name'];
		newFeature.decs = row['desc'];
		
		document.getElementById("name").innerHTML="name:"+newFeature.name;
		document.getElementById("desc").innerHTML="desc:"+newFeature.decs;
	}
}
function updateData(){
	YARINDB.transaction(
		function (transaction) {
			var data = ['fengsheng yang','I am fengsheng']; 
			transaction.executeSql("UPDATE yarin SET name=?, desc=? WHERE id = 1", [data[0], data[1]]);
		}
	);	
	selectAll();
}
function ddeleteTables(){
	YARINDB.transaction(
		function (transaction) {
			transaction.executeSql("DROP TABLE yarin;", [], nullDataHandler, errorHandler);
		}
	);
	console.log("Table 'page_settings' has been dropped.");
}
注意onLoad中的初始化工作
function initLocalStorage(){
	if (window.localStorage) {
		textarea.addEventListener("keyup", function() {
			window.localStorage["value"] = this.value;
			window.localStorage["time"] = new Date().getTime();
		}, false);
	} else {
		alert("LocalStorage are not supported in this browser.");
	}
}

window.onload = function() {
	initDatabase();
	initLocalStorage();
}

HTML5地理位置服务在Android中的应用:

Android中:

	//启用地理定位
webSettings.setGeolocationEnabled(true);
//设置定位的数据库路径
webSettings.setGeolocationDatabasePath(dir);
//配置权限(同样在WebChromeClient中实现)
public void onGeolocationPermissionsShowPrompt(String origin, 
			   GeolocationPermissions.Callback callback) {
	callback.invoke(origin, true, false);
	super.onGeolocationPermissionsShowPrompt(origin, callback);
}

在Manifest中添加权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

HTML5中 通过navigator.geolocation对象获取地理位置信息:

常用的navigator.geolocation对象有以下三种方法:

  1. //获取当前地理位置

     navigator.geolocation.getCurrentPosition(success_callback_function, error_callback_function, position_options)
    
  2. //持续获取地理位置

     navigator.geolocation.watchPosition(success_callback_function, error_callback_function, position_options)
    
  3. 清除持续获取地理位置事件

     navigator.geolocation.clearWatch(watch_position_id)
    

----其中success_callback_function为成功之后处理的函数,error_callback_function为失败之后返回的处理函数,参数position_options是配置项

在JS中的代码:

//定位
function get_location() {
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(show_map,handle_error,{enableHighAccuracy:false,maximumAge:1000,timeout:15000});
	} else {
		alert("Your browser does not support HTML5 geoLocation");
	}
}
	
function show_map(position) {
	var latitude = position.coords.latitude;
	var longitude = position.coords.longitude;
	var city = position.coords.city;
	//telnet localhost 5554
	//geo fix -82.411629 28.054553
	//geo fix -121.45356 46.51119 4392
	//geo nmea $GPGGA,001431.092,0118.2653,N,10351.1359,E,0,00,,-19.6,M,4.1,M,,0000*5B
	document.getElementById("Latitude").innerHTML="latitude:"+latitude;
	document.getElementById("Longitude").innerHTML="longitude:"+longitude;
	document.getElementById("City").innerHTML="city:"+city;
}
	
function handle_error(err) {
	switch (err.code) {
	case 1:
		alert("permission denied");
		break;
	case 2:
		alert("the network is down or the position satellites can't be contacted");
		break;
	case 3:
		alert("time out");
		break;
	default:
		alert("unknown error");
		break;
	}
}

----其中position对象包含很多数据 error代码及选项 可以查看文档

构建HTML5离线应用:

需要提供一个cache manifest文件,理出所有需要在离线状态下使用的资源
例如:

CACHE MANIFEST 
#这是注释
images/sound-icon.png
images/background.png
clock.html 
clock.css 
clock.js  

NETWORK: 
test.cgi
CACHE: 
style/default.css
FALLBACK: 
/files/projects /projects


在html标签中声明 <html manifest="clock.manifest">?

HTML5离线应用更新缓存机制

分为手动更新和自动更新2种

自动更新:

在cache manifest文件本身发生变化时更新缓存 资源文件发生变化不会触发更新

手动更新:

使用window.applicationCache

	if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
		window.applicationCache.update();
	} 

在线状态检测

HTML5 提供了两种检测是否在线的方式:navigator.online(true/false) 和 online/offline事件。

在Android中构建离线应用:

//开启应用程序缓存
webSettingssetAppCacheEnabled(true);
String dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
//设置应用缓存的路径
webSettings.setAppCachePath(dir);
//设置缓存的模式
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//设置应用缓存的最大尺寸
webSettings.setAppCacheMaxSize(1024*1024*8);
//扩充缓存的容量
public void onReachedMaxAppCacheSize(long spaceNeeded,
			long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
	quotaUpdater.updateQuota(spaceNeeded * 2);
}

Android与JS之间的互相调用

在JS中调用Android的函数方法

	final class InJavaScript {
    public void runOnAndroidJavaScript(final String str) {
    	handler.post(new Runnable() {
            public void run() { 
                TextView show = (TextView) findViewById(R.id.textview);
                show.setText(str);
            }
        });
    }
}

//把本类的一个实例添加到js的全局对象window中,
//这样就可以使用window.injs来调用它的方法
webView.addJavascriptInterface(new InJavaScript(), "injs");

在JavaScript中调用:

function sendToAndroid(){
	var str = "Cookie call the Android method from js";
	window.injs.runOnAndroidJavaScript(str);//调用android的函数
}

在Android中调用JS的方法:

在JS中的方法:

function getFromAndroid(str){
	document.getElementById("android").innerHTML=str;
}

在Android调用该方法:

Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
	public void onClick(View arg0) {
	 	//调用javascript中的方法
	    webView.loadUrl("javascript:getFromAndroid('Cookie call the js function from Android')");
	}
});

Android中处理JS的警告,对话框等

在Android中处理JS的警告,对话框等需要对WebView设置WebChromeClient对象:

	//设置WebChromeClient
webView.setWebChromeClient(new WebChromeClient(){
	//处理javascript中的alert
	public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
		//构建一个Builder来显示网页中的对话框
		Builder builder = new Builder(MainActivity.this);
		builder.setTitle("Alert");
		builder.setMessage(message);
		builder.setPositiveButton(android.R.string.ok,
			new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					result.confirm();
				}
			});
		builder.setCancelable(false);
		builder.create();
		builder.show();
		return true;
	};
	//处理javascript中的confirm
	public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
		Builder builder = new Builder(MainActivity.this);
		builder.setTitle("confirm");
		builder.setMessage(message);
		builder.setPositiveButton(android.R.string.ok,
			new AlertDialog.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					result.confirm();
				}
			});
		builder.setNegativeButton(android.R.string.cancel,
			new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					result.cancel();
				}
			});
		builder.setCancelable(false);
		builder.create();
		builder.show();
		return true;
	};
		
	@Override
	//设置网页加载的进度条
	public void onProgressChanged(WebView view, int newProgress) {
		MainActivity.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress * 100);
		super.onProgressChanged(view, newProgress);
	}
	//设置应用程序的标题title
	public void onReceivedTitle(WebView view, String title) {
		MainActivity.this.setTitle(title);
		super.onReceivedTitle(view, title);
	}
});

Android中的调试:

通过JS代码输出log信息:

Js代码: console.log("Hello World");
Log信息: Console: Hello World http://www.example.com/hello.html :82

在WebChromeClient中实现onConsoleMesaage()回调方法,让其在LogCat中打印信息:

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
	public void onConsoleMessage(String message, int lineNumber, String sourceID) {
		Log.d("MyApplication", message + " -- From line "
			+ lineNumber + " of "
			+ sourceID);
	}
});

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
	public boolean onConsoleMessage(ConsoleMessage cm) {
		Log.d("MyApplication", cm.message() + " -- From line "
			+ cm.lineNumber() + " of "
			+ cm.sourceId() );
		return true;
	}
});

---ConsoleMessage 还包括一个 MessageLevel 表示控制台传递信息类型。

您可以用messageLevel()查询信息级别,以确定信息的严重程度,然后使用适当的Log方法或采取其他适当的措施。

后面的内容在下篇中继续

猜你喜欢

转载自blog.csdn.net/sslinp/article/details/83412164