WebView shouldOverrideUrlLoading and redirect问题

问题:客户端界面中打开安卓市场某款产品的下载界面。点击下载按钮后,并不走客户端写在shouldOverrideUrlLoading中的处理逻辑。导致该包不能下载。

ps:安卓市场下载按钮是通过js跳转的。


原来,android平台下,在ApiLevel小于11的情况下,webview的shouldOverrideUrlLoading并不是每次都会调用。

所以需要添加平台适配。或者将放在shouldOverrideUrlLoading中的逻辑放在onPageStarted方法中去处理。


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.

  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:

  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.


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值