无法在工作配置文件模式下以编程方式在 android 7 上安装 apk(来源未知)

Unable to install apk on android 7 programmatically in work profile mode (Unknown sources)

我正在尝试以“Work Profile”模式 (BYOD) 编程方式安装 apk。但是有一个我无法解决的问题:无法在 android 版本 7.0(24) 和 7.1(25) 中安装 apk。将出现一个带有此消息的弹出对话框:

Your administrator doesn't allow installation of apps obtained from unknown sources

瞧我怎么做:

val uri = FileProvider.getUriForFile(context,authority,File(filePath))   
val openFileIntent = Intent(Intent.ACTION_VIEW)
openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
openFileIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
openFileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
openFileIntent.data = uri
context.startActivity(openFileIntent)

在清单中:

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

和file_provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>

这就是我找到解决方案的方式:

    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
        devicePolicyManager.setSecureSetting(
            componentName,
            Settings.Secure.INSTALL_NON_MARKET_APPS,
            "1"
        )
    } else {
        devicePolicyManager.addUserRestriction(componentName,
UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES)
    }