我已经使用DownloadManager构建了从链接下载文件的应用程序,并在下载时显示进度轮。下载完成后,我发送广播接收器将进度轮改为下载的图标。
现在面临一个问题,如果我从通知托盘取消下载,我没有得到任何广播,因此进度轮不会停止。
任何人都知道如何才能获得取消下载的广播?
答案 0 :(得分:1)
要获得下载过程,您需要将downloadManager注册到广播接收器。
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
mContext.registerReceiver(downloadReceiver, filter);
这里,广播接收器是:
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkDownloadStatus(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1));
}
};
因此,当下载取消或成功下载或出现任何错误时,您将获得状态。即使你取消通知。您可以通过以下方式查看状态:
private void checkDownloadStatus(long downloadReference) {
DownloadManager.Query myDownloadQuery = new DownloadManager.Query();
myDownloadQuery.setFilterById(downloadReference);
//向下载管理器查询已请求的下载。 游标光标= downloadManager.query(myDownloadQuery); if(cursor.moveToFirst()){
//column for status
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnIndex);
//column for reason code if the download failed or paused
int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
int reason = cursor.getInt(columnReason);
//get the download filename
String statusText = "";
String reasonText = "";
switch (status) {
case DownloadManager.STATUS_FAILED:
statusText = "STATUS_FAILED";
switch (reason) {
case DownloadManager.ERROR_CANNOT_RESUME:
reasonText = "ERROR_CANNOT_RESUME";
break;
case DownloadManager.ERROR_DEVICE_NOT_FOUND:
reasonText = "ERROR_DEVICE_NOT_FOUND";
break;
case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
reasonText = "ERROR_FILE_ALREADY_EXISTS";
break;
case DownloadManager.ERROR_FILE_ERROR:
reasonText = "ERROR_FILE_ERROR";
break;
case DownloadManager.ERROR_HTTP_DATA_ERROR:
reasonText = "ERROR_HTTP_DATA_ERROR";
break;
case DownloadManager.ERROR_INSUFFICIENT_SPACE:
reasonText = "ERROR_INSUFFICIENT_SPACE";
break;
case DownloadManager.ERROR_TOO_MANY_REDIRECTS:
reasonText = "ERROR_TOO_MANY_REDIRECTS";
break;
case DownloadManager.ERROR_UNHANDLED_HTTP_CODE:
reasonText = "ERROR_UNHANDLED_HTTP_CODE";
break;
case DownloadManager.ERROR_UNKNOWN:
reasonText = "ERROR_UNKNOWN";
break;
}
break;
case DownloadManager.STATUS_PAUSED:
statusText = "STATUS_PAUSED";
switch (reason) {
case DownloadManager.PAUSED_QUEUED_FOR_WIFI:
reasonText = "PAUSED_QUEUED_FOR_WIFI";
break;
case DownloadManager.PAUSED_UNKNOWN:
reasonText = "PAUSED_UNKNOWN";
break;
case DownloadManager.PAUSED_WAITING_FOR_NETWORK:
reasonText = "PAUSED_WAITING_FOR_NETWORK";
break;
case DownloadManager.PAUSED_WAITING_TO_RETRY:
reasonText = "PAUSED_WAITING_TO_RETRY";
break;
}
break;
case DownloadManager.STATUS_PENDING:
statusText = "STATUS_PENDING";
break;
case DownloadManager.STATUS_RUNNING:
statusText = "STATUS_RUNNING";
break;
case DownloadManager.STATUS_SUCCESSFUL:
statusText = "STATUS_SUCCESSFUL";
break;
}
}
}
如果出错,您可以停止进度条。