我試圖重現DownloadManager在我的應用程序中的Notification欄中顯示的相同進度,但是我的進度永遠不會發布。我試圖使用runOnUiThread()來更新它,但由於某種原因它沒有被更新。使用DownloadManager顯示下載活動內部進度
我下載:
String urlDownload = "https://dl.dropbox.com/s/ex4clsfmiu142dy/test.zip?token_hash=AAGD-XcBL8C3flflkmxjbzdr7_2W_i6CZ_3rM5zQpUCYaw&dl=1";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlDownload));
request.setDescription("Testando");
request.setTitle("Download");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "teste.zip");
final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
final long downloadId = manager.enqueue(request);
final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
new Thread(new Runnable() {
@Override
public void run() {
boolean downloading = true;
while (downloading) {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadId);
Cursor cursor = manager.query(q);
cursor.moveToFirst();
int bytes_downloaded = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
final double dl_progress = (bytes_downloaded/bytes_total) * 100;
runOnUiThread(new Runnable() {
@Override
public void run() {
mProgressBar.setProgress((int) dl_progress);
}
});
Log.d(Constants.MAIN_VIEW_ACTIVITY, statusMessage(cursor));
cursor.close();
}
}
}).start();
我statusMessage方法:
private String statusMessage(Cursor c) {
String msg = "???";
switch (c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
msg = "Download failed!";
break;
case DownloadManager.STATUS_PAUSED:
msg = "Download paused!";
break;
case DownloadManager.STATUS_PENDING:
msg = "Download pending!";
break;
case DownloadManager.STATUS_RUNNING:
msg = "Download in progress!";
break;
case DownloadManager.STATUS_SUCCESSFUL:
msg = "Download complete!";
break;
default:
msg = "Download is nowhere in sight";
break;
}
return (msg);
}
我的日誌可以正常使用,我下載運行時說! 「正在下載」當它完成「下載完成!」,但我的進度不會發生同樣的情況,爲什麼?我真的需要一些幫助,其他的邏輯做的真的很感激
難道是你的文件太小了,並且在進度發佈之前下載完成了嗎?下載查詢在您的任務中返回什麼?如果任務僅在一段時間後執行,則可能會在主線程上執行其他一些長時間運行的操作。 – 2013-04-03 19:59:52
我更新了代碼,你現在可以看看嗎?關於文件長度不算太小,我可以在通知欄 – 2013-04-03 21:00:40