Search code examples
androidandroid-permissionsandroid-11

NameNotFoundException when calling getPackageInfo on Android 11


After setting targetSdkVersion to 30 (Android 11) I'm getting android.content.pm.PackageManager$NameNotFoundException when doing packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS) on packages that I know exists.

The stacktrace is as follows:

android.content.pm.PackageManager$NameNotFoundException: com.google.android.apps.maps
        at android.app.ApplicationPackageManager.getPackageInfoAsUser(ApplicationPackageManager.java:202)
        at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:174)

Solution

  • As stated in https://developer.android.com/preview/privacy/package-visibility:

    Android 11 changes how apps can query and interact with other apps that the user has installed on a device. Using the new element, apps can define the set of other apps that they can access. This element helps encourage the principle of least privilege by telling the system which other apps to make visible to your app, and it helps app stores like Google Play assess the privacy and security that your app provides for users.

    If your app targets Android 11, you might need to add the element in your app's manifest file. Within the element, you can specify apps by package name or by intent signature.

    So you either have to stop what you are doing, or request to access information about certain packages, or - if you have reasons for it - use the permission QUERY_ALL_PACKAGES.

    Query and interact with specific packages

    To query and interact with specific packages you would update your AndroidManifest.xml like this:

    <manifest ...>
        ...
        <queries>
            <package android:name="com.example.store" />
            <package android:name="com.example.services" />
        </queries>
        ...
         <application ...>
        ...
    </manifest>
    

    Query and interact with all apps

    I have an app that needs to be able to ask for information for all apps. All you have to do is to add the following to AndroidManifest.xml:

    <manifest ...>
         ...
         <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
         ...
         <application ...>
         ...
    </manifest>