Android 在代码中安装 APK

737 阅读1分钟

废话不说,先上代码

public void installApkFile(Context context, String filePath) {
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    context
                    , context.getPackageName() + ".fileprovider"
                    , apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

关于在代码中安装 APK 文件,在 Android N 以后,为了安卓系统为了安全考虑,不能直接访问软件,需要使用 fileprovider 机制来访问、打开 APK 文件。

适配 Android 各版本

第一步

在清单文件(manifests.xml)application 标签中增加 标签:

<application>
    <!--其他的配置项-->
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="你的包名.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>
    <!--其他的配置项-->
</application>

注意两点内容:

  1. android:authorities="你的包名.fileprovider" 这个属性要设置成你自己的包名;
  2. 标签下 android:resource="@xml/file_paths" 是要配置的 xml 文件。

第二步

在 res/xml 下增加文件: file_paths.xml 该文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="your_name"
        path="your_path" />
</paths>

上面的两个属性要根据自己的使用来配置,其中 external-path 就是手机的外置存储目录。

第三步

很重要的一步,解决了 8.0 系统安装没有效果的问题:

在清单文件(manifests.xml)添加如下权限:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />