使用DownLoadManager实现下载apk功能,并安装
使用downloadmanager需要了解:
DownloadManager.Request();
DownloadManager.Query();
Request用来发送请求
Query 用来查询下载信息
DownLoadManager具体使用:
首先构建一个Request对象, 参数是一个下载请求地址
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
在通知栏显示下载
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
设置下载路径
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
获取DownLoadManager
DownloadManager mDownloadManager = (DownloadManager)mContext.getSystemService(Context.DOWNLOAD_SERVICE);
放置到下载队列里,执行下载
downloadId = mDownloadManager.enqueue(request);
下载过程中我们还可以监听下载的状态
获取Query
DownloadManager.Query query = new DownloadManager.Query();
只包含带有给定id的下载。
query.setFilterById(downloadId);
查询,获得Cursor
Cursor cursor = mDownloadManager.query(query);
下载状态:
if(cursor.moveToFirst()){
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
switch (status) {
//下载暂停
case DownloadManager.STATUS_PAUSED:
break;
//下载延迟
case DownloadManager.STATUS_PENDING:
break;
//正在下载
case DownloadManager.STATUS_RUNNING:
break;
//下载完成
case DownloadManager.STATUS_SUCCESSFUL:
Log.d("dog","下载成功");
installAPK();
break;
//下载失败
case DownloadManager.STATUS_FAILED:
Log.d("dog","下载失败");
Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
break;
}
}
获取下载总大小,当前大小
if(cursor.moveToFirst()){
//当前大小
int curtSize= cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
//下载总大小
int totalSize = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
}
使用完别忘记关闭
cursor.close();
下载完成之后开始安装:
private void installAPK() {
File apkFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
mContext.startActivity(intent);
}
可以使用计时器来监听刷新下载进度,下载完成后调用系统安装.