android webview拦截非http
时间: 2023-07-18 15:19:33 浏览: 74
在WebView中拦截非http链接,例如file://、tel://、mailto://等,可以通过重写shouldOverrideUrlLoading方法来实现。以下是示例代码:
```java
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("http") || url.startsWith("https")) {
// 如果链接以http或https开头,则继续加载链接
return false;
} else {
// 如果链接不是以http或https开头,则拦截链接并处理
if (url.startsWith("tel:")) {
// 如果链接以tel:开头,则打电话
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
} else if (url.startsWith("mailto:")) {
// 如果链接以mailto:开头,则发送邮件
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{url.substring(7)});
startActivity(Intent.createChooser(intent, "Send Email"));
} else if (url.startsWith("file:")) {
// 如果链接以file:开头,则打开本地文件
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
startActivity(intent);
}
return true;
}
}
});
```
在上面的示例中,我们首先检查链接是否以http或https开头。如果是,则继续加载链接。如果链接不是以http或https开头,则根据链接的协议进行相应的处理。例如,如果链接以"tel:"开头,则打电话;如果链接以"mailto:"开头,则发送邮件;如果链接以"file:"开头,则打开本地文件。最后,返回true以拦截链接。
请注意,如果您需要在Android 7.0及更高版本上拦截非HTTP链接,建议您使用shouldOverrideUrlLoading(WebView view, WebResourceRequest request)方法,因为shouldOverrideUrlLoading(WebView view, String url)方法在7.0及更高版本上已经过时。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)