使用Android自带的DownloadManager下载ApK并安装

2026-02-06 06:17:55 8817

一、在 AndroidManifest.xml 中的准备

进行网络请求,需要申请权限

安装 app ,需要申请 权限

读取手机设备,需要申请 权限

注册一个 receiver 来监听下载完成和下载过程中点击通知栏的事件

二、DownLoadManager 下载功能

/**

* 使用 DownloaderManager 下载

*

* @param downloadUrl

* @param fileName

* @param mimetype

*/

public static void downLoadUrl(String downloadUrl, String fileName, String mimetype) {

// 创建下载请求

DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));

/*

* 设置在通知栏是否显示下载通知(下载进度), 有 3 个值可选:

* VISIBILITY_VISIBLE: 下载过程中可见, 下载完后自动消失 (默认)

* VISIBILITY_VISIBLE_NOTIFY_COMPLETED: 下载过程中和下载完成后均可见

* VISIBILITY_HIDDEN: 始终不显示通知

*/

request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

request.setVisibleInDownloadsUi(true);

// 设置通知的标题和描述

request.setTitle(fileName);

request.setDescription(fileName);

request.setMimeType(mimetype);

// 设置下载文件的保存位置

File saveFile = new File(Environment.getExternalStorageDirectory(), fileName);

request.setDestinationUri(Uri.fromFile(saveFile));

/*

* 2. 获取下载管理器服务的实例, 添加下载任务

*/

DownloadManager manager = (DownloadManager) SystemUtil.getAppContext().getSystemService(Context.DOWNLOAD_SERVICE);

// 将下载请求加入下载队列, 返回一个下载ID

long downloadId = manager.enqueue(request);

Log.d("Download", "downloadId=" + downloadId + "\tsaveFile=" + saveFile.getAbsolutePath());

}

三、下载完成监听

/**

* 检查下载状态,是否下载成功

*/

public static void checkStatus(Context context) {

DownloadManager manager = getDownLoadManager();

DownloadManager.Query query = new DownloadManager.Query();

// 执行查询, 返回一个 Cursor (相当于查询数据库)

Cursor cursor = manager.query(query);

if (!cursor.moveToFirst()) {

cursor.close();

}

int id = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_ID));

//通过下载的id查找

query.setFilterById(id);

// 获取下载好的 apk 路径

String localFilename = null;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

} else {

localFilename = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));

}

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("Download", "localFilename:" + localFilename);

//下载完成安装APK

installApp(context, localFilename);

cursor.close();

break;

case DownloadManager.STATUS_FAILED:

//下载失败

cursor.close();

break;

default:

break;

}

}

}

自定义DownLoadManagerReceiver,实现监听

public class DownLoadManagerReceiver extends BootBroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

String action = intent.getAction();

if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {

Log.d("Download", "用户点击了通知");

// 点击下载进度通知时, 对应的下载ID以数组的方式传递

long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);

Log.d("Download", "ids: " + Arrays.toString(ids));

long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);

Log.d("Download", "id: " + completeDownloadId);

//这里可以做暂停下载功能

} else if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

Log.d("Download", "下载完成");

DownLoadUtil.checkStatus(context);

}

}

}

四、调起apk安装

/**

* 安装apk

*

* @param context

* @param path

*/

private static void installApp(Context context, String path) {

Log.d("Download", "installApp: StorageState = " + Environment.getExternalStorageState());

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

// Uri.parse(path).getPath()去除 file://

File targetFile = new File(Uri.parse(path).getPath());

Log.i("Download", "targetFile: " + targetFile.getPath() + "\ttargetFile = " + targetFile.getAbsolutePath() + "\ttargetFile 是否存在:" + targetFile.exists());

if (targetFile.exists()) {//先判断文件是否已存在

Log.i("Download", "targetFile: ---" + targetFile.getPath());

//1. 创建 Intent 并设置 action

Intent intent = new Intent(Intent.ACTION_VIEW);

//2. 设置 category

intent.addCategory(Intent.CATEGORY_DEFAULT);

Uri uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", targetFile);

//添加 flag ,不记得在哪里看到的,说是解决:有些机器上不能成功跳转的问题

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件

//3. 设置 data 和 type

intent.setDataAndType(uri, "application/vnd.android.package-archive");

//3. 设置 data 和 type (效果和上面一样)

//intent.setDataAndType(Uri.fromFile(targetFile),"application/vnd.android.package-archive");

//intent.setDataAndType(Uri.parse("file://" + targetFile.getPath()),"application/vnd.android.package-archive");

//4. 启动 activity

context.startActivity(intent);

}

}

}

在 AndroidManifest 中 声明 provider:

android:name="android.support.v4.content.FileProvider"

android:authorities="${applicationId}.fileprovider"

android:exported="false"

android:grantUriPermissions="true">

android:name="android.support.FILE_PROVIDER_PATHS"

android:resource="@xml/file_path"

tools:replace="android:resource"/>

file_path.xml文件在 res 的 xml 目录下:

这里为什么要申明 FileProvider ?[参考链接]

原因在于使用file://Uri会有一些风险,比如:

文件是私有的,接收file://Uri的app无法访问该文件。

在Android6.0之后引入运行时权限,如果接收file://Uri的app没有申请READ_EXTERNAL_STORAGE权限,在读取文件时会引发崩溃。

因此,google提供了FileProvider 类,使用它可以生成content://Uri来替代file://Uri,所以要在应用间共享文件,应发送一项 content:// URI,并授予 URI 临时访问权限。

FileProvider是android support v4包提供的,是ContentProvider的子类,便于将自己app的数据提供给其他app访问。

在app开发过程中需要用到FileProvider的主要有

相机拍照以及图片裁剪

调用系统应用安装器安装apk(应用升级)

分享文件

有时候广告第三方也会引入 FileProvider,这就会导致 FileProvider 重复,只需要重新建立一个空类继承 FileProvider 里面什么都不用写,在 AndroidManifest 中申明自定义的 FileProvider 即可

至此从下载 Apk 到下载完成后自动调起安装就完成了

这里有个小 tip:

可以通过下载的路径,获取到 ApkInfo,得到对应的包信息