Androids WebView class provides a method called shouldOverrideUrlLoading to intercept the loading of the requested URLs.
This gives us the ability to suppress loading of the given URL or handle a URL in the external browser for example.

If you want to prevent the webview from loading the URL you have to return true. Otherwise the url is forwarded to the webview as usual.

view plain copy to clipboard print ?
  1. _webView.setWebViewClient(new WebViewClient() {  
  2.   @Override  
  3.   public boolean shouldOverrideUrlLoading(WebView view, String url) {  
  4.     boolean shouldOverride = false;  
  5.     if (url.startsWith("https://")) { //NON-NLS  
  6.       // DO SOMETHING  
  7.       shouldOverride = true;  
  8.     }  
  9.     return shouldOverride;  
  10.   }  
  11. }  

This mechanism works fine for all URLs triggered by a user tapping on a link.

Unfortunately this method does not get invoked if the URLs source is a redirect on devices running Android < 3.0 (API Level 10 and lower).
Although it will be invoked an works just fine on devices with Android >= 3.0 (API Level 11 and up).

Android < 3.0 -> shouldOverrideUrlLoading will not be called on redirects

Android >= 3.0 -> shouldOverrideUrlLoading will be called even on redirects

You can find some fellow developers facing the same issue.

As a Workaround we use the recommended onPageStarted(WebView view, String url, Bitmap favicon)

Usage is quite the same as shouldOverrideUrlLoading:

view plain copy to clipboard print ?
  1. _webView.setWebViewClient(new WebViewClient() {  
  2.   @Override  
  3.   public void onPageStarted(WebView view, String url, Bitmap favicon){  
  4.     if (url.startsWith("https://")) { //NON-NLS  
  5.       view.stopLoading();  
  6.       // DO SOMETHING  
  7.     }  
  8.   }  
  9. }   

With view.stopLoading the webview will stop loading of the new URL and still show the current content. This equals the behavior of shouldOverrideUrlLoading returning true.

The advantage is it works on all Android versions.

However the drawback is onPageStarted is invoked AFTER the page was requested form server. That means, the request is already sent to the server even if the response is afterward ignored.

The method shouldOverrideUrlLoading would let you omit the request BEFORE it is sent. So you would be able to save the outgoing web request.

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. Android(安卓)性能优化
  2. Android 调用系统摄像头
  3. android的shader渲染器
  4. Android EditText输入框被键盘遮挡问题解
  5. Android-常用UI控件(Spinner/AutoComplet
  6. Activity之间传递类对象
  7. Android实现翻页功能原理
  8. Android(安卓)selector背景选择器的使用
  9. Android(安卓)RecyclerView学习(一)----
  10. 玩转Android---2D图形及动画---图片处理