Install_app_from_unknown_sources 对话框在 Android 10 中不显示

问题描述 投票:0回答:0

我是安卓新手。我制作了一个应用程序,其中一部分用于下载文件。我想打开从我的应用程序下载的文件。但我的应用程序无法在某些 Android 10 手机中打开

apk
文件,并显示“解析包时出现问题”错误。

谷歌搜索此错误后发现主要问题是我的应用程序不允许 install_app_from_unknown_sources 。在 Android 11 及更高版本中,android 向用户显示一个对话框,并让用户在 android 设置中更改它,但在 Android 10 中,除了解析错误之外,不显示任何内容。

这就是我打开文件的方式:

public class DownloadFilesAction {
    public void openFile(String fileName) {
        File file = this.getFileByFileNameInDownloadsDirectory(fileName);
        if (file == null)
            return;
        Context context = MyApplication.getContext();
        Intent intent = createIntentToOpenFile(file);
        PackageManager packageManager = context.getPackageManager();
        if (packageManager != null && intent != null) {
            try {
                if (intent.resolveActivity(packageManager) != null) {
                    context.startActivity(intent);
                }
            } catch (Exception ignore) {
            }
        }
    }

    @Nullable
    private File getFileByFileNameInDownloadsDirectory(String fileName) {
        File targetFile = null;
        try {
            File downloadsDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File foundFile = new File(downloadsDirectory, fileName);
            if (foundFile.exists()) {
                targetFile = foundFile;
            }
        } catch (Exception ignore) {
        }
        return targetFile;
    }

    @Nullable
    private Intent createIntentToOpenFile(File file) {
        Context context = MyApplication.getContext();
        Uri fileUri = this.getFilePathUri(file);
        try {
            String mime = context.getContentResolver().getType(fileUri);
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(fileUri, mime);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
            return intent;
        } catch (Exception ignore) {
        }
        return null;
    }

    private Uri getFilePathUri(File file) {
        Context context = MyApplication.getContext();
        return FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
    }
}

在清单文件中我拥有此权限:

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

如何让 android 显示我的应用程序的 install_app_from_unknown_sources 对话框?

android apk android-permissions
© www.soinside.com 2019 - 2024. All rights reserved.