我在尝试从基于WebView的应用程序上的服务器下载文件时遇到问题。该代码实际上适用于android 4.4.2的Galaxy S4,但不适用于相同版本的android的Nexus 5。
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.toLowerCase().contains("video") || url.toLowerCase().contains("mp4")) {
String cookie = CookieManager.getInstance().getCookie(url);
DownloadManager mdDownloadManager = (DownloadManager) MainActivity.this
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.addRequestHeader("Cookie", cookie);
request.setDescription(getString(R.string.download_video));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle(getString(R.string.app_name));
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, getFileName(url));
request.setMimeType("video/mp4");
mdDownloadManager.enqueue(request);
}
webViewPreviousState = PAGE_REDIRECTED;
view.loadUrl(appendAndroidClientIdentification(url));
return true;
}
检查日志时发现,试图通过Nexus 5设备下载文件:
I/DownloadManager﹕ Download 1755 starting
W/DownloadManager﹕ Aborting request for download 1755: can't know size of download, giving up
I/DownloadManager﹕ Download 1755 finished with status CANNOT_RESUME
答案:
问题出在服务器端。我使用的是来自rails的send_data方法。此方法不会在标头中发送ContentLength,这就是某些设备中出现错误的原因。
要修复此问题,只需添加到应用程序.rb文件:
config.middleware.use Rack::ContentLength
问题出在服务器端。我使用的是来自rails的方法send_data
。此方法不在标头中发送ContentLength
,这是某些设备中出现错误的原因。
要解决此问题,只需添加到application.rb
:
config.middleware.use Rack::ContentLength