这更多是出于好奇而提出的问题,而不是需要解决的实际问题。我制作了一个包含 WebView 的 Android 应用程序。我使用了 should override URL 方法,以便单击的任何链接都将在 WebView 中打开。
后来我决定将文件从服务器下载到用户设备。不幸的是我之前没有见过 setDownloadListener 方法。现在,当用户单击链接时,不会启动下载。
据我所知,我需要使用正确的代码(即下载侦听器或 HttpClient)更新应用程序,这是可以的。
(冒着听起来像个白痴的风险)我想知道,是否有任何方法可以通过服务器的操作使 WebView 下载文件而无需更改代码?
我猜想该功能不在 WebView 中,这可能就是 WebView 打开浏览器来下载文件的原因。只是想也许我错过了一些让它发挥作用的东西。我对此很陌生。
您应该能够通过 webview JavascripInterface 在 android 中使用 DownloadManager 启动下载。我自己正在尝试这样做,到目前为止还没有成功。我可能对 webview 和 DownloadManager 工作的上下文有问题。如果它能工作,我会带着一些代码回来:)
UPDATE:
下面的代码对我来说效果很好。您可以使用以下内容:(请注意,您只能使用 Android 2.3+ 的下载管理器)
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;
}
});
在上面的代码中,我管理 .apk 文件、.mp3 文件的链接,所有其他链接将由 webview (普通 HTML 页面)处理
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)