将文件下载到Android WebView(代码中没有下载事件或HTTPClient)
这与其说是一个真正需要解决的问题,不如说是一个出于好奇的问题。我制作了一个Android应用程序,其中包含一个网络视图。我使用了“应该覆盖URL”方法,以便在WebView中打开单击的任何链接 后来我决定将一个文件从服务器下载到用户设备。不幸的是,我以前没有见过setDownloadListener方法。当用户现在单击链接时,下载不会启动 据我所知,我需要用适当的代码更新应用程序,即下载侦听器或HttpClient,这是可以的 (冒着听起来像个白痴的风险)我想知道,有没有办法通过服务器上的一个操作,让WebView下载一个文件而无需更改代码将文件下载到Android WebView(代码中没有下载事件或HTTPClient),android,webview,Android,Webview,这与其说是一个真正需要解决的问题,不如说是一个出于好奇的问题。我制作了一个Android应用程序,其中包含一个网络视图。我使用了“应该覆盖URL”方法,以便在WebView中打开单击的任何链接 后来我决定将一个文件从服务器下载到用户设备。不幸的是,我以前没有见过setDownloadListener方法。当用户现在单击链接时,下载不会启动 据我所知,我需要用适当的代码更新应用程序,即下载侦听器或HttpClient,这是可以的 (冒着听起来像个白痴的风险)我想知道,有没有办法通过服务器上的一个操
我猜WebView中没有这个功能,这可能就是WebView打开浏览器下载文件的原因。我只是在想,也许我错过了一些让它发挥作用的东西。我对这个很陌生 我认为webview将只下载并呈现文本/html内容和多部分。其余的将被定向到您正在看到的下载客户端
- 赫罗吉特
在上面的代码中,我管理指向.apk文件、.mp3文件的链接,所有其他链接都将由webview(普通HTML页面)处理。你说得对。它实际上并不直接指向下载客户端。我自己不得不称之为下载意图,但你是对的,它只下载html。
myWebView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.d("WEB_VIEW_TEST", "error code:" + errorCode + " - " + description);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// handle different requests for different type of files
// this example handles downloads requests for .apk and .mp3 files
// everything else the webview can handle normally
if (url.endsWith(".apk")) {
Uri source = Uri.parse(url);
// Make a new request pointing to the .apk url
DownloadManager.Request request = new DownloadManager.Request(source);
// appears the same in Notification bar while downloading
request.setDescription("Description for the DownloadManager Bar");
request.setTitle("YourApp.apk");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// save the file in the "Downloads" folder of SDCARD
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "SmartPigs.apk");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
else if(url.endsWith(".mp3")) {
// if the link points to an .mp3 resource do something else
}
// if there is a link to anything else than .apk or .mp3 load the URL in the webview
else view.loadUrl(url);
return true;
}
});