Android 下载管理器 - 无法知道下载的大小
-
21-12-2019 - |
题
我在尝试在基于 WebView 的应用程序上从服务器下载文件时遇到问题。这段代码实际上 适用于 Galaxy S4 与安卓4.4.2 但不适用于 Nexus 5 与相同版本的Android。
@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
解决方案
问题出在服务器端。我正在使用该方法 send_data
从铁轨。此方法不发送 ContentLength
在标头中,这是某些设备中出现错误的原因。
要解决此问题,只需添加到 application.rb
:
config.middleware.use Rack::ContentLength
不隶属于 StackOverflow