我有以下问题:每当我用DownloadManager下载一个文件时,它都会被下载两次(以"filename.extension"one_answers"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()
方法只调用一次。我希望你能帮我找出错误。
不幸的是,DownloadManager存在缺陷,无法在所有设备上正常工作。此处报告您的问题:https://code.google.com/p/android/issues/detail?id=18462
我在使用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代码,但它应该是解决方法本身的一个很好的表示