以编程方式在Android 8中安装apk(API 26)

v.d*_*v.d 31 android apk

我写了一个方法在所有版本的android中安装apk,它的工作原理直到android 8.但似乎android 8不响应这种方法

install_apk(File file) {
        try {
            if (file.exists()) {
                String[] fileNameArray = file.getName().split(Pattern.quote("."));
                if (fileNameArray[fileNameArray.length - 1].equals("apk")) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        Uri downloaded_apk = getFileUri(context, file);
                        Intent intent = new Intent(Intent.ACTION_VIEW).setDataAndType(downloaded_apk,
                                "application/vnd.android.package-archive");
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        context.startActivity(intent);
                    } else {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(file),
                                "application/vnd.android.package-archive");
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
Run Code Online (Sandbox Code Playgroud)

这个方法用于获取api> = 23的uri

Uri getFileUri(Context context, File file) {
        return FileProvider.getUriForFile(context,
                context.getApplicationContext().getPackageName() + ".HelperClasses.GenericFileProvider"
                , file);
    }
Run Code Online (Sandbox Code Playgroud)

小智 57

您应该添加新权限.

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
Run Code Online (Sandbox Code Playgroud)

  • @Gavin除了此权限,还需要更多代码吗?我想从URL下载.apk文件并安装它。添加此权限后,它也不会安装。 (3认同)