Without further ado, let’s start with the code

public void installApkFile(Context context, String filePath) {
        File apkFile = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(
                    context
                    , context.getPackageName() + ".fileprovider"
                    , apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }
Copy the code

As for the installation of APK files in the code, after Android N, for the sake of Android system security, the software cannot be directly accessed, so you need to use the FileProvider mechanism to access and open APK files.

Compatible with various Android versions

The first step

Add a tag to the manifests file application tag:

<application> <! -- Other configuration items --> < Provider Android :name="android.support.v4.content.FileProvider"
        android:authorities="Your package name.fileProvider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"/> </provider> <! Other configuration items --> </application>Copy the code

Two points to note:

  1. Android :authorities=” file_provider “;
  2. Under the Android :resource=”@xml/file_paths” tag is the XML file to be configured.

The second step

Add the file file_paths.xml under res/ XML:

<? xml version="1.0" encoding="utf-8"? > <paths> <external-path name="your_name"
        path="your_path" />
</paths>
Copy the code

The two properties above are configured according to their own use, where external-path is the phone’s external storage directory.

The third step

An important step to solve the problem of 8.0 system installation not working:

Add the following permissions to the manifests file:

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