一定要定义一个 DownloadChangeObserver extends ContentObserver,在其复写的 onChange()方法里实时第检测下载的状况,然后去做需要做的事情
@Override
public void onChange(boolean selfChange) {
//每次 database变化时 就触发此事件,开始具体查询
Log.e(TAG, "onChange: --");
// ProgressUtils.showProgress(context,"正在打开中,请稍后......");
checkStatus();
}
private void checkStatus() {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
//执行查询 返回一个Cursor
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
//文件地址
String fileLocalName = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Log.e(TAG, "checkStatus:fileLocalName: " + fileLocalName);
// 已下载的字节大小
long downloadedSoFar = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
// 下载文件的总字节大小
long totalSize = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
Log.e(TAG, "checkStatus:downloadedSoFar " + downloadedSoFar + " totalSize" + totalSize);
//
// if(status!=DownloadManager.STATUS_FAILED&&downloadedSoFar<totalSize){
// Log.e(TAG, "status loading: ---" );
// ProgressUtils.showProgress(context,"zhengzai----");
// }
switch (status) {
case DownloadManager.STATUS_PAUSED:
break;
case DownloadManager.STATUS_FAILED:
ProgressUtils.hideProgress();
ToastUtil.show(context, "下载文件失败,请重试");
break;
case DownloadManager.STATUS_RUNNING:
ProgressUtils.showProgress(context, "正在打开中......");
break;
case DownloadManager.STATUS_PENDING:
Log.e(TAG, "pending: ");
break;
case DownloadManager.STATUS_SUCCESSFUL:
ProgressUtils.hideProgress();
//获取下载文件的Uri
Uri downloadFileUri = downloadManager.getUriForDownloadedFile(downloadId);
openFile(downloadFileUri);
// IntentUtils.getPdfFileIntent(file,context);
Log.e(TAG, "STATUS_SUCCESSFUL: ----pdfFile" + file.getName());
break;
default:
break;
}
}
}
网友评论