你想要的只是部分可能的,并且总是需要异常处理。
在 Android Webview 中,关于处理链接点击,您可以执行以下操作:
1:设置webviewclient拦截任何点击的url:
设置 web 客户端允许您检查单击了哪个 url,并为每个不同的 url 指定一个操作。
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
// you can try to open the url, you can also handle special urls here
view.loadUrl(url);
return false; // do not handle by default action
}
});
您可以根据自己的喜好设置难度,以处理确实需要首先下载的非常特定的文件类型,但要在后台下载它们而不加载外部浏览器,您可以执行以下操作:
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// handle different requests for different type of files
// Download url when it is a music file
if (url.endsWith(".mp3")) {
Uri source = Uri.parse(url);
DownloadManager.Request mp3req = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
mp3req.setDescription("Downloading mp3..");
mp3req.setTitle("song.mp3");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mp3req.allowScanningByMediaScanner();
mp3req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
mp3req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "song.mp3");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(mp3req);
}
else if(url.endsWith(".something")) {
// do something else
}
//or just load the url in the web view
else view.loadUrl(url);
return true;
}
2:拦截任何下载的文件:
您还可以使用此代码在开始下载时进行拦截。这样您就可以直接在您的应用中使用下载的内容。
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
//do whatever you like with the file just being downloaded
}
});
无保证,总是需要异常处理
WebView 可以处理的内容类型,取决于所使用的 WebView 的版本,在当前时间点,WebView 只能处理某些类型。对于某些类型,需要特殊权限,例如 html5 视频需要 hardware acceleration。
另一个支持示例:Android 3.0 之前不支持 SVG。还有许多其他示例,其中在最新版本的 WebView 中实现了对某些类型的支持,但在旧版本中不存在。
您可以在此处阅读有关当前 WebView 实现的更多信息:https://developer.chrome.com/multidevice/webview/overview
天下没有免费的午餐