Android 13 (SDK 33): PackageManager.getPackageInfo(String, int) deprecated. what is the alternative?

33k Views Asked by At

Starting from API level 33 the getPackageInfo(String, int) method of PackageManager class is deprecated. Documentation suggests to use getPackageInfo(String, PackageInfoFlags) instead. But that function is only available from API level 33.

My current code:

val pInfo = context.packageManager.getPackageInfo(context.packageName, 0)

Is this how it should be now?

val pInfo = context.getPackageInfo()

@Suppress("DEPRECATION")
fun Context.getPackageInfo(): PackageInfo {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0))
    } else {
        packageManager.getPackageInfo(packageName, 0)
    }
}
2

There are 2 best solutions below

3
CommonsWare On BEST ANSWER

Is this how it should be now?

Yes, though I've gotten out of the practice of using TIRAMISU in favor of the actual underlying Int.

Ideally, Google would add stuff to PackageManagerCompat for these changes, and perhaps they will now that Android 13 is starting to ship to users.

4
mtrakal On

If you are using Kotlin, you can add extension function to your project:

fun PackageManager.getPackageInfoCompat(packageName: String, flags: Int = 0): PackageInfo =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(flags.toLong()))
    } else {
        @Suppress("DEPRECATION") getPackageInfo(packageName, flags)
    }

and after just call packageManager.getPackageInfoCompat(packageName) or add another flag, if you need.