Check if application is installed - Android
Since Android 11 (API level 30), most user-installed apps are not visible by default. In your manifest, you must statically declare which apps you are going to get info about, as in the following:
<manifest>
<queries>
<!-- Explicit apps you know in advance about: -->
<package android:name="com.example.this.app"/>
<package android:name="com.example.this.other.app"/>
</queries>
...
</manifest>
Then, @RobinKanters' answer works:
private boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
// ...
// This will return true on Android 11 if the app is installed,
// since we declared it above in the manifest.
isPackageInstalled("com.example.this.app", pm);
// This will return false on Android 11 even if the app is installed:
isPackageInstalled("another.random.app", pm);
Learn more here:
- The migration documentation
- The dedicated documentation page (has more information)
- The official blog post
Try this:
private boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
It attempts to fetch information about the package whose name you passed in. Failing that, if a NameNotFoundException
was thrown, it means that no package with that name is installed, so we return false
.
Note that we pass in a PackageManager
instead of a Context
, so that the method is slightly more flexibly usable and doesn't violate the law of Demeter. You can use the method without access to a Context
instance, as long as you have a PackageManager
instance.
Use it like this:
public void someMethod() {
// ...
PackageManager pm = context.getPackageManager();
boolean isInstalled = isPackageInstalled("com.somepackage.name", pm);
// ...
}
Note: From Android 11 (API 30), you might need to declare <queries>
in your manifest, depending on what package you're looking for. Check out the docs for more info.