Android WebViewClient 处理跳转URL

前言

最近代码里和WebView有很多的交互,webview是android中的浏览器控件,这里主要介绍一下webview如何重载WebViewClient类来控制URL加载。

使用WebViewClient

使用WebViewClinet主要是继承WebViewClient父类,根据需要重写其中的方法,并在WebView中进行配置,示例代码如下:

	webView = (WebView) findViewById(R.id.webview);
	webView.setWebViewClient(new ExampleWebViewClient());
	private class ExampleWebViewClient extends WebViewClient {
		@Override
		public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
			handler.proceed();
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return true;
		}

		@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 onLoadResource(WebView view, String url) {
			super.onLoadResource(view, url);
		}
	}

WebViewClient方法

1. shouldOverrideUrlLoading(WebView view, String url)

官方注释:Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided,by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url. This method is not called for requests using the POST "method".

翻译:当一个新的url要在当前WebView进行加载的时候,这个方法给应用一个机会来控制url的处理。如果WebView没有setWebViewClient,则默认操作是WebView将询问Activity Manager获取合适的handler处理url。如果WebView设置了setWebViewClient,返回true代表当前应用来处理url,返回false则代表当前webview来处理url。如果http请求是POST方法,该方法将不会被调用。

代码示例:

		/**
		 * 所有以www.example.com开头的url调用系统浏览器打开 其他的url在当前webview打开
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (url.indexOf("http://www.example.com") != -1) {
				// 调用系统默认浏览器处理url
				view.stopLoading();
				view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
				return true;
			}
			return false;
		}

2. shouleOverrideKeyEvent(WebView view, KeyEvent event)

官方注释:Give the host application a chance to handle the key event synchronously. e.g. menu shortcut key events need to be filtered this way. If return true, WebView will not handle the key event. If return false, WebView will always handle the key event, so none of the super in the view chain will see the key event. The default behavior returns false.

翻译:给当前应用一个机会来异步处理按键事件。返回true,WebView将不会处理该按键事件,返回false,WebView将处理该按键事件。默认返回是false。

3. onPageStarted(WebView view, String url, Bitmap favicon)和onPageFinished(WebView view, String url)

官方注释:Notify the host application that a page has started loading. This method is called once for each main frame load so a page with iframes or framesets will call onPageStarted one time for the main frame. This also means that onPageStarted will not be called when the contents of an embedded frame changes, i.e. clicking a link whose target is an iframe.

翻译:当页面开始加载时被调用。但是,当页面被嵌套时(例如iframe里有一个链接跳转),该方法将不会被调用。(今天就遇到了这种情况,可以通过重载onLoadResource来控制url跳转)

官方注释:Notify the host application that a page has finished loading. This method is called only for main frame. When onPageFinished() is called, the rendering picture may not be updated yet. To get the notification for the new Picture, use onNewPicture(WebView, Picture).

翻译:在页面加载结束时被调用。

代码示例:

		// 获取页面加载时间
		private long startTime;
		private long endTime;
		private long spendTime;

		@Override
		public void onPageFinished(WebView view, String url) {
			endTime = System.currentTimeMillis();
			spendTime = endTime - startTime;
			Toast.makeText(view.getContext(), "spend time is:" + spendTime, Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			startTime = System.currentTimeMillis();
		}

4. onLoadResource(WebView view, String url)

官方注释:Notify the host application that the WebView will load the resource specified by the given url.

翻译:通知应用程序WebView将要加载指定url的资源,每一个资源(例如图片,嵌套url,js,css文件)。(可以通过该方法处理iframe嵌套的url)

代码示例:

		@Override
		public void onLoadResource(WebView view, String url) {
			if (url.indexOf("http://www.example.com") != -1 && view != null) {
				view.stopLoading();
				view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
			}
		}
时间: 2024-08-10 23:17:53

Android WebViewClient 处理跳转URL的相关文章

手机平板等移动端适配跳转URL的js代码

<script type="text/javascript"> if(/AppleWebKit.*mobile/i.test(navigator.userAgent) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(navigator.userAgent)

paip.微信菜单直接跳转url和获取openid流程总结

#------不能直接跳转,贝儿提示不安全的链接.. #-------使用auth跳转. //todox 直接转到..  direct goto ViewButton skrechCard = new ViewButton("刮刮卡o428,view," + "https://open.weixin.qq.com/connect/oauth2/authorize?" + "appid="+appId+"&" + &qu

JS判断是否是微信页面,判断手机操作系统(ios或android)并跳转到不同下载页面

JS判断客户端是否是iOS或者Android 参考:http://caibaojian.com/browser-ios-or-android.html 1 function is_weixin() { 2 var ua = window.navigator.userAgent.toLowerCase(); 3 if (ua.match(/MicroMessenger/i) == 'micromessenger') { 4 return true; 5 } else { 6 return fals

Android实现界面跳转

实现界面跳转的代码如下: 第一种: Intent mIntent =  new Intent();mIntent.setClassName(mcureeActivity.this, nextActivity.class);startActivity(mIntent) 第二种: Intent mIntent =  new Intent();mIntent.setClassName("com.android.test", "com.android.test.next")

ecshop设置一个子类对应多个父类并指定跳转url的修改方法

这是一篇记录在日记里面的技术文档,其实是对ecshop的二次开发.主要作用是将一个子类对应多个父类,并指定条跳转url的功能.ecshop是一款在线购物网站,感兴趣的可以下载源码看看.我们看看具体是怎么修改的. 1.数据库表“表前缀_category”添加如下字段 alter TABLE `ga_category` add `assign_child` varchar(255) default NULL; alter TABLE `ga_category` add `jump_url` varc

Android的Activity跳转动画各种效果整理

Android的Activity跳转就是很生硬的切换界面.其实Android的Activity跳转可以设置各种动画,本文整理了一些,还有很多动画效果,就要靠我们发挥自己的想象力 大家使用Android的原生UI都知道,Android的Activity跳转就是很生硬的切换界面.其实Android的Activity跳转可以设置各种动画.下面给大家看看效果:  实现非常简单,用overridePendingtransition(int inId, int outId)即可实现.inId是下一界面进入效

android content provider 中的URL解析总是出问题?求指导!!!

java.lang.IllegalArgumentException: Unknown URL content:// 不管是自己写或者用别的的代码在我的eclipse中都是报这个错误 很怪,我的URL地址绝对没有写错,是不是和使用版本有关系?我的google提供的eclipse,sdk用的2.3.3 android content provider 中的URL解析总是出问题?求指导!!!

Android之Activity跳转

简述 如果把每个activity看成一个页面的话,那么activity之间的跳转和页面的之间的跳转基本上是一样的.首先需要监听一个事件,当这个事件发生的时候,就进行跳转.html中有个<a src="..."></a>的链接标签,当我们点击这个链接的时候就会发送跳转.这是因为浏览器会自动监听这个链接是否被点击,如果被点击那个浏览器自己执行跳转动作.但是在Android中就没这么简单,程序员需要自己去监听某个事件,当这个事件发生的时候,需要自己指定目的Activi

Android Activity延迟跳转

有时候我们发现一些APP的引导页面,是等一会在调到主页面的,其实这个时候他是在处理数据操作,我们今天就模拟一下Android  Activity延迟跳转的功能!其实非常简单,就是加上一段代码:如下 new Handler().postDelayed(new Runnable() { public void run() { //你需要跳转的地方的代码 finish(); } }, 2000); //延迟2秒跳转 Android Activity延迟跳转