来源:https://blog.51cto.com/u_16213385/12575668
整个安装过程一般可以分为以下几个步骤:获取 APK 文件的路径、请求权限、调用安装 Intent、完成安装
在 Android 7.0(API Level 24)及以上版本中,安装应用包需要用户人工干预并且设备需要开启未知来源的安装选项。在开始安装之前,确保你具有存储和安装应用的权限。
在你的 AndroidManifest.xml 文件中添加如下权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
安装代码,apkPath:/data/data/com.study.apptest/download/upgrade/apptest.1.0.1.apk
private void installApk(String apkPath) {
    File apkFile = new File(apkPath);
    if (!apkFile.exists()) {
        Toast.makeText(this, "APK文件不存在", Toast.LENGTH_SHORT).show();
        return;
    }

    Uri apkUri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", apkFile);
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        intent.setData(apkUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    } else {
        apkUri = Uri.fromFile(apkFile);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}

使用 FileProvider,为了在 Android 7.0 及以上版本中安全地共享文件,你需要在 AndroidManifest.xml 中声明 FileProvider,如下:

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

你还需要创建 res/xml/file_paths.xml 文件以配置路径,比如:

<paths>
    <external-path name="external_files" path="." />
</paths>

 

posted on 2024-12-30 15:01  邢帅杰  阅读(48)  评论(0编辑  收藏  举报