banner
李大仁博客

李大仁博客

天地虽大,但有一念向善,心存良知,虽凡夫俗子,皆可为圣贤。

Android強制使用WebView不調用系統或外部瀏覽器

HTML5 HYBIRD 混合 APP 需要在 H5 頁面中打開第三方網站(例如:百度),android 默認不在當前 WebView 中打開,反而會調用系統或外部瀏覽器,解決辦法是自己重寫 WebViewClient,覆蓋 shouldOverrideUrlLoading 並讓其返回 True。

實現代碼

mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
//webview 自己加載 URL,讓後通知系統不需要 HandleURL
view.loadUrl(url);
return true;
}
});

原因可以從 Android 源代碼中可知,True if the host application wants to leave the current WebView and handle the url itself, otherwise return false。

/** 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".
@param view The WebView that is initiating the callback.
@param url The url to be loaded.
@return True if the host application wants to leave the current WebView and handle the url itself, otherwise return false.
*/

public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}

需要注意一點問題,如果你的代碼中有撥打電話(tel:),發送郵件 (mailto:) 的話,需要在實現代碼時對 URL 簡單篩選一下才好

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。