android下载完APK后调起安装

首先,这里涉及到两个问题:

1.android 7.0的FileProvider

2.android 8.0的安装“未知”APK功能

一、使用FileProvider

因为android 7.0不能直接以file:///的形式访问apk文件,所以需要使用FileProvider

1.在AndroidManifest的application下注册

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="cn.test.zz.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
        </provider>

2.自定义file_paths.xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="downlaod" path="download"/>
</paths>

这里的name可以随意命名,path是文件的目录。如果有子目录可以继续加,比如:download/app

3.使用FileProvider来访问

/**
     * 7.0安装应用
     */
    public void start7Install(File file) {
        File imagePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "downlaod");
        File newFile = new File(imagePath, mDownloadFileName);
        Uri apkUri = FileProvider.getUriForFile(context, "cn.test.zz.fileprovider", newFile);//在AndroidManifest中的android:authorities值
        Intent install =new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        startActivity(install);
    }

需要注意的是,要是android 7.0一下的手机还是要用旧方法启动

/**
     * 普通调起安装
     * @param file
     */
    private void installApp(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

二、Android 8.0特殊权限申请

if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
                    if(!getPackageManager().canRequestPackageInstalls()){
                        //打开权限
                        Uri packageURI = Uri.parse("package:" + getPackageName());
                        //注意这个是8.0新API
                        Intent intent1 = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                        startActivity(intent1);
                        installAPK(file);
                    }else{
                        //有权限,直接安装
                        installAPK(file);
                    }
                }else{
                    //安卓8.0以下,直接安装
                    installAPK(file);
                }

猜你喜欢

转载自blog.csdn.net/zz1667654468/article/details/84568920
今日推荐