Android DownloadManager下载文件时,会先下载一个临时文件,然后在下载完成时将其重命名为实际文件。但是,如果您使用默认的下载完成通知打开文件,它将打开这个临时文件,而不是实际文件。
以下是解决此问题的代码示例:
1.创建一个BroadcastReceiver处理DOWNLOAD_COMPLETE action:
public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
String uriString = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Uri uri = null;
if (uriString != null) {
uri = Uri.parse(uriString);
if (uri != null) {
String mime = downloadManager.getMimeTypeForDownloadedFile(downloadId);
Intent viewIntent = new Intent(Intent.ACTION_VIEW);
viewIntent.setDataAndType(uri, mime);
viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(viewIntent);
}
}
}
}
cursor.close();
}
}
}
2.在AndroidManifest.xml中注册BroadcastReceiver:
使用此方法,当下载完成时,我们可以获取实际文件的URI并使用适当的Intent打开它。