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

柴岳
2023-12-01

一、在 AndroidManifest.xml 中的准备

  1. 进行网络请求,需要申请<uses-permission android:name="android.permission.INTERNET" />权限
  2. 安装 app ,需要申请<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> 权限
  3. 读取手机设备,需要申请 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.READ_PHONE_STATE" /> 权限
    4、注册一个 receiver 来监听下载完成和下载过程中点击通知栏的事件
  <receiver android:name=".reciever.DownLoadManagerReceiver">
            <intent-filter>
                <!-- 配置 点击通知 和 下载完成 两个 action -->
                <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED"/>
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE"/>
            </intent-filter>
        </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);

            }
        }
    }

至此从下载 Apk 到下载完成后自动调起安装就完成了
这里有个小 tip:

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

 类似资料: