Android 在WebView中打开附件
我在Android 在WebView中打开附件,android,android-webview,Android,Android Webview,我在WebView上有一个附件。当我点击它时,什么也没发生。我知道在WebView上打开附件,但解决方案是基于条件的。是否有一些解决方案可以在不放置条件的情况下打开它,因为我的应用程序支持多个扩展附件我不想下载附件。 这就是我现在正在做的,这些只是几个扩展: if ((url.contains(".pdf") || url.contains(".xml") || url.contains(".xlsx") || url.contains(".docx") || url.contains(".pp
WebView
上有一个附件。当我点击它时,什么也没发生。我知道在WebView上打开附件,但解决方案是基于条件的。是否有一些解决方案可以在不放置条件的情况下打开它,因为我的应用程序支持多个扩展附件我不想下载附件。这就是我现在正在做的,这些只是几个扩展:
if ((url.contains(".pdf") || url.contains(".xml") || url.contains(".xlsx") || url.contains(".docx") || url.contains(".ppt"))) {
url = org.apache.commons.lang3.StringUtils.join("http://docs.google.com/gview?embedded=true&url=", url);
browser.loadUrl(url);
}
您想要的只是部分可能,并且始终需要异常处理。 在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视频需要硬件加速。 另一个支持示例:在Android 3.0之前不支持SVG。还有许多其他的例子,在WebView的最新版本中实现了对某些类型的支持,但在旧版本中不存在 您可以在此处阅读有关当前WebView实现的更多信息:
没有免费午餐这回事因为webview只能处理有限数量的内容类型,所以总是会附加字符串。@e4c5:放置条件是唯一的解决方案?您是否在WebViewClient.shouldInterceptRequest中使用该代码?