我遇到以下问题:每当我使用DownloadManager下载文件时,都会下载两次(以“filename.extension”和“filename-1.extension”的方式保存)。这是我的代码:
public void download() {
Request request = new Request(Uri.parse(_wrapper.getURL()));
request.setTitle(getFileName(_wrapper.getURL()));
request.setVisibleInDownloadsUi(false);
request.setDestinationInExternalFilesDir(_context, null, "/" + getFileName(_wrapper.getURL()));
_downloadID = _downloadManager.enqueue(request);
}
public BroadcastReceiver getDownloadFinishedBroadcastReceiver() {
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context pContext, Intent pIntent) {
String action = pIntent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Query query = new Query();
query.setFilterById(_downloadID);
Cursor cursor = _downloadManager.query(query);
if (cursor.moveToFirst()) {
File file = new File(ScruloidConstants.APPLICATION_DIRECTORY);
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
String path = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
_wrapper.setFilePath(path);
_wrapper.setLastDownloaded(new Date());
if (_listener != null) {
_listener.onDownloadProjectTaskFinished(new TaskResult<ProjectWrapper>(_wrapper));
}
}
else if (status == DownloadManager.STATUS_FAILED) {
int reason = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
DownloadFailedException ex = new DownloadFailedException(reason);
if (_listener != null) {
_listener.onDownloadProjectTaskFinished(new TaskResult<ProjectWrapper>(ex));
}
}
}
}
}
};
return receiver;
}
ProjectWrapper _wrapper
只是一个保存数据的简单类,那里没有逻辑。 _listener
只在回调方法上显示一个Toast小消息。我调试了我的应用程序,以使download()
方法仅被调用一次。我希望你能帮我找到错误。
答案 0 :(得分:2)
不幸的是,DownloadManager存在问题,无法在所有设备上正常运行。您的问题在此处报告:https://code.google.com/p/android/issues/detail?id=18462
答案 1 :(得分:0)
我在使用API 21的移动设备上遇到了相同的错误,如果要设置请求目标的文件名等于已下载的最后一个文件之一,则在创建请求之前进行了变通方法验证或如果它是下载的所有预览的子字符串
if (!mLastMediaDownloadedId.any { it.contains(outputFile.name) }) {
mLastMediaDownloadedId.add(outputFile.name)
val url =
AppConstants.AWS_MEDIA_BUCKET_PATH + scoutObjectType.endPoint() + "$scoutObjectId.png"
val request = DownloadManager.Request(Uri.parse(url))
.setDestinationUri(Uri.fromFile(outputFile))
.setTitle("Downlading media")
.setDescription("Downloading image medias")
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
.setAllowedOverRoaming(true)
.setAllowedOverMetered(true)
val downloadId = it.enqueue(request)
downloadIds.add(downloadId)
downloadId
}
其中“ outputFile”是要下载的文件名本身,在您的情况下,应为“ filename.extension”
PS:对不起,Kotlin代码,但这对于变通办法本身应该是一个很好的表示方式