添加以下代码来设置下载管理器的错误处理:
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
long downloadId = downloadManager.enqueue(request);
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(downloadId);
Cursor cursor = downloadManager.query(query);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnIndex);
if (status == DownloadManager.STATUS_SUCCESSFUL) {
// File downloaded successfully
} else if (status == DownloadManager.STATUS_FAILED) {
// Download failed, check error code
int errorCode = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_REASON));
if (errorCode == DownloadManager.ERROR_CANNOT_RESUME
|| errorCode == DownloadManager.ERROR_DEVICE_NOT_FOUND
|| errorCode == DownloadManager.ERROR_FILE_ALREADY_EXISTS
|| errorCode == DownloadManager.ERROR_FILE_ERROR
|| errorCode == DownloadManager.ERROR_HTTP_DATA_ERROR
|| errorCode == DownloadManager.ERROR_INSUFFICIENT_SPACE
|| errorCode == DownloadManager.ERROR_TOO_MANY_REDIRECTS
|| errorCode == DownloadManager.ERROR_UNHANDLED_HTTP_CODE
|| errorCode == DownloadManager.ERROR_UNKNOWN) {
// Handle error
}
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));