失敗的頁面加載的url都是自定義scheme開頭的(alipays://、weixin://)。webview只能識別http://或https://開頭的url, 因此如果要識別其他的scheme (如: alipays、weixin、mailto、tel ... 等等), 你就要自行處理. 一般其他的scheme都是由原生APP處理, 即用一個Intent去調起能處理此scheme開頭的url的APP. 代碼如下:
Intent intent =newIntent(Intent.ACTION_VIEW, Uri.parse(customUrl));
startActivity(intent);
用intent處理自定義的scheme開頭的url時, 代碼必須加上try...catch...?, 應為如果你的手機上沒有安裝處理那個scheme的應用 (整個手機上沒有一個應用能處理那個scheme), 那么就會crash (這跟隱式啟動Activity是一個道理) !!!
二. 解決方法
給WebView設置WebViewClient并重寫WebViewClient的shouldOverrideUrlLoading()方法
完整代碼如下:
WebViewClient webViewClient =newWebViewClient(){
@OverridepublicbooleanshouldOverrideUrlLoading(WebView view, String url){
if(url ==null) return? false;
if(url.startsWith("http://") || url.startsWith("https://") ) {? ? ?//處理http和https開頭的url? ??
view.load(url);
return true;
?}? ?else{
try{
Intent intent =newIntent(Intent.ACTION_VIEW, Uri.parse(url));? ? ? ? ? ? ? ??
?startActivity(intent);?
??return? true;? ?
}???catch(Exception e) {? ? ? ? //防止crash (如果手機上沒有安裝處理某個scheme開頭的url的APP, 會導致crash)
return false;? ? }
? }
};
webview.setWebViewClient(webViewClient);