共计 2604 个字符,预计需要花费 7 分钟才能阅读完成。
基础使用:
DownloadManager.Request request;
try{
request = new DownloadManager.Request(Uri.parse(“String url”));
// 放入下载队列
Context appContext = getApplicationContext();
DownloadManager manager = (DownloadManager)appContext.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}catch (Exception e){
e.printStackTrace();
return;
}
加入下载队列后可以获得一个下载 ID 用于创建下载进度观察者或者下载完成的广播通知
long downloadId = manager.enqueue(request);
下载进度观察者:
final DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
getContentResolver().registerContentObserver(Uri.parse(“content://downloads/my_downloads”), true, new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
int[] bytesAndStatus = new int[]{-1, -1, 0};
DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
Cursor cursor = null;
try {
cursor = dm.query(query);
if (cursor != null && cursor.moveToFirst()) {
// 已经下载文件大小
bytesAndStatus[0] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
// 下载文件的总大小
bytesAndStatus[1] = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
// 下载状态
bytesAndStatus[2] = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
// 计算下载进度
float progress = (float)bytesAndStatus[0]/bytesAndStatus[1];
// 当进度完全执行好了记得 注销观察者 不注销的话 可能会多跑几次
if(progress == 1){
getContentResolver().unregisterContentObserver(this);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
});
注册广播接收者
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long ID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (ID == downloadId) {
// 执行完成后的代码
Toast.makeText(getApplicationContext(), “ 任务:” + downloadId + ” 下载完成!”, Toast.LENGTH_LONG).show();
// 记得注销广播接收者 不注销的话这个会一直在的
unregisterReceiver(this);
}
}
};
registerReceiver(broadcastReceiver, intentFilter);
其他:1. 保存路径问题
request.setDestinationInExternalPublicDir(“ 保存路径 ”,” 保存的文件名称 ”);
2. 通知栏显示下载信息
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
request.setTitle(“ 下载 ”);
request.setDescription(“ 应用正在下载 ”);
request.setAllowedOverRoaming(false);
3. 个人使用目的:下载 apk,完成后调用安装
String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager dManager = (DownloadManager) context.getSystemService(serviceString);
// 根据下载管理获取下载文件的 URI 自己写 Uri.pase(“ 文件路径 ”) 也是可以的
Uri downloadFileUri = dManager.getUriForDownloadedFile(downloadId);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 该语句会授予临时的访问权限 否则会秒退
intent.setDataAndType(fileuri, “application/vnd.android.package-archive”);
startActivity(intent);