Android安装APK一直闪退,报错没权限

大神们,我在android里调用代码安装apk,报错: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.google.android.packageinstaller/com.android.packageinstaller.InstallStart}: java.lang.SecurityException: UID 10077 does not have permission to content://com.smartparking.provider/inner_app_cache/SmartParkingV2.0.91.apk [user 0],可以帮忙看一下吗?已经焦头烂额好几天啦!!

代码如下:

Intent intent = new Intent(Intent.ACTION_VIEW);
            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
                intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                uri = Uri.fromFile(file);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            startActivity(intent);

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


引用 皆我百晓生 小程序回复内容作答:
您好!根据您提供的错误信息和代码,发现您在使用FileProvider时可能出现了权限问题。

首先,请确保您已经在AndroidManifest.xml文件中添加了相应的权限:

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

其次,您可能需要在provider_paths.xml文件中对文件路径进行相应的配置。请检查并确认以下内容是否正确:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="." />
</paths>

这个配置允许您使用外部存储中的文件进行共享。

最后,您可以尝试在调用安装APK的代码前,动态请求安装权限:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    if (!getPackageManager().canRequestPackageInstalls()) {
        // 发起请求安装未知来源应用的权限
        Uri packageUri = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
        startActivityForResult(intent, 1);
    }
}

这段代码会检查并在需要时请求安装未知来源应用的权限。

希望以上方案能够帮到您解决问题!如果仍有疑问,请随时追问。