Home » Android » install apk programmatically in android 8 (API 26)

install apk programmatically in android 8 (API 26)

Posted by: admin April 23, 2020 Leave a comment

Questions:

I wrote a method to install apk in all version of android and it works until android 8 . but it seems android 8 do not response to this method

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();
        }
    }

and this method for get uri on api >= 23

Uri getFileUri(Context context, File file) {
        return FileProvider.getUriForFile(context,
                context.getApplicationContext().getPackageName() + ".HelperClasses.GenericFileProvider"
                , file);
    }
How to&Answers:

You should be add a new permission.

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