我在我的项目中使用DonwloadManager,在官方参考中有关于ERROR_FILE_ALREADY_EXISTS的描述。
问题是我在使用相同的URL和目标URI时从未出现过这个错误。 DownloadManager
始终下载相同的文件,只需在文件名末尾添加一些数字,以便与之前的下载不同。
入队代码非常简单且工作得很好,除了这个奇怪的东西允许你重新下载已经下载的文件:
Uri uri = Uri.parse(url);
Request request = new Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE |
DownloadManager.Request.NETWORK_WIFI);
request.setVisibleInDownloadsUi(false);
Uri fileDestinationUri = Uri.parse("file://" + new File(destinationFilePath);
request.setDestinationUri(fileDestinationUri);
long downloadId = downloadManager.enqueue(request);
我有BroadcastReciever
正在听android.intent.action.DOWNLOAD_COMPLETE
意图:
@Override
public void onReceive(Context context, Intent intent) {
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
Query query = new Query();
query.setFilterById(downloadId);
Cursor cur = dm.query(query);
if (cur.moveToFirst()) {
int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
switch (cur.getInt(columnIndex)) {
case DownloadManager.STATUS_SUCCESSFUL:
Log.d(Settings.TAG_APP, "Download successfully completed.");
break;
case DownloadManager.STATUS_FAILED:
int columnReasonIndex = cur.getColumnIndex(DownloadManager.COLUMN_REASON);
Log.d(Settings.TAG_APP, "Download failed with error: " + cur.getInt(columnReasonIndex));
break;
}
}
cur.close();
cur = null;
}
我发现另外2个问题以某种方式连接到我的问题,但没有答案:
Android - Overwrite files when downloading via Download Manager
How can i make download manager overwrite an exisiting file instead of renaming the file in android