androidandroid-intentandroid-install-apkandroid-package-managers

How to run Android app or install on PlayStore if unavailable for API30?


I have a android app where I want to run other apps. If these apps are not installed already, I would like to open PlayStore to let the user install them:

var info : ApplicationInfo? = null
try {
    info = pm.getApplicationInfo(packageName, 0) as ApplicationInfo
} catch (e: PackageManager.NameNotFoundException){
    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse("market://details?id=$packageName")
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    context.startActivity(intent)
}

if (info != null) {
    val intent = pm.getintentForPackage(packageName) as Intent
    context.startActivity(intent)
}

This snippet works so far good for API 26 (Android 8) for instance. But for API 30 (Android 11) the getApplicationInfo() throws a NameNotFoundException always, even when I already installed the app.

Whats wrong here?


Solution

  • On Android 11, methods on PackageManager like getApplicationInfo() no longer work by default. You need to either:

    In your case, the <queries> element is probably a safe choice, assuming that your list of application IDs that you are looking for is knowable at compile time.