Search code examples
androidandroid-studioandroid-10.0packageinstaller

Is there any way to use PackageInstaller below API level 21?


My application minSdkVersion is 19 and application installs 3rd party app using following code,

Intent intent = Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(android.net.Uri.fromFile(new java.io.File(APK_PATH)),
                        "application/vnd.android.package-archive");
intent.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

I have Added permission in manifest file,

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

The above code is working well up to android version 9, but in Android 10 is not working and no logs found. I have gone through some docs, ACTION_VIEW or ACTION_INSTALL_PACKAGE is deprecated on Android 10. PackageInstaller is a new API for install 3rd party apps but PackageInstaller is added in API level 21.

Is there any way to use PackageInstaller below API level 21? How can I install 3rd party app in Android 10??


Solution

  • In order to integrate both APIs you can use simple if statement that decides which API you should use.

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.L) {
        // use PackageInstaller. No errors, no exceptions 
    } else {
        Intent intent = Intent(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(android.net.Uri.fromFile(new java.io.File(APK_PATH)),
                            "application/vnd.android.package-archive");
        intent.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    

    Build.VERSION.SDK_INT is the SDK number of which is used on a device where your application is running.

    Build.VERSION_CODES.L is a constant value:

    /**
     * Temporary until we completely switch to {@link #LOLLIPOP}.
     * @hide
     */
    public static final int L = 21;
    

    That is the official way to handle SDK differences. Here is an example from Android documentation. Search for >= Build.VERSION_CODES on that page.