我正在使用DownloadManager类下载pdf文件。它在我的带有Android 7.1.1的Nexus 6p上的android 5.0A 但的华为GRA-L09上运行良好我遇到以下行为:
下载文件后,我尝试通过意图Action_View打开它,以便用pdf viewer打开它。但是当我尝试打开它时,我收到一个错误,即文件大小为0并且无法打开。如果我等待大约10秒钟,我就可以打开文件了。
这是DownloadManager的源代码:
DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/Download", "test.pdf");
long enqueue = dm.enqueue(request);
这是BroadcastReceiver的源代码:
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(enqueue);
Cursor cursor = null;
String uri = null;
String mime = null;
try {
cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
// process download
uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
mime = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_MEDIA_TYPE));
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
openFile(Uri.parse(uri), mime);
}
}
};
private void openFile(final Uri fileLocation, final String mimeType) {
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(fileLocation, mimeType);
Log.d(Constants.TAG, "Downloaded file Uri: " + fileLocation.toString() + " mime:" + mimeType);
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent chooserIntent = Intent.createChooser(objIntent, getString(R.string.choose_application));
startActivity(chooserIntent);//Starting the pdf viewer
}
我尝试打开它而不是pdf的意图,只需按状态栏上的通知图标即可。同样的事情发生了,好像文件被锁定或尚未下载。
更新:在Nexus设备上,当我在下载完成后检查file.length()时,我得到文件大小= 0。在华为GRA-L09上,文件大小为1882670。 那么为什么我要为大小为0的文件下载完成的广播?