We have installed applications programmatically.
Cleaner solution (without try-catch) than the accepted answer (based on AndroidRate Library):
public static boolean isPackageExists(@NonNull final Context context, @NonNull final String targetPackage) {
List<ApplicationInfo> packages = context.getPackageManager().getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
if (targetPackage.equals(packageInfo.packageName)) {
return true;
}
}
return false;
}
A simpler implementation using Kotlin
fun PackageManager.isAppInstalled(packageName: String): Boolean =
getInstalledApplications(PackageManager.GET_META_DATA)
.firstOrNull { it.packageName == packageName } != null
And call it like this (seeking for Spotify app):
packageManager.isAppInstalled("com.spotify.music")
You can do it using Kotlin extensions :
fun Context.getInstalledPackages(): List<String> {
val packagesList = mutableListOf<String>()
packageManager.getInstalledPackages(0).forEach {
if ( it.applicationInfo.sourceDir.startsWith("/data/app/") && it.versionName != null)
packagesList.add(it.packageName)
}
return packagesList
}
fun Context.isInDevice(packageName: String): Boolean {
return getInstalledPackages().contains(packageName)
}
@Egemen Hamutçu s answer in kotlin B-)
private fun isAppInstalled(context: Context, uri: String): Boolean {
val packageInfoList = context.packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES)
return packageInfoList.asSequence().filter { it?.packageName == uri }.any()
}
If you know the package name, then this works without using a try-catch block or iterating through a bunch of packages:
public static boolean isPackageInstalled(Context context, String packageName) {
final PackageManager packageManager = context.getPackageManager();
Intent intent = packageManager.getLaunchIntentForPackage(packageName);
if (intent == null) {
return false;
}
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return !list.isEmpty();
}
Somewhat cleaner solution than the accepted answer (based on this question):
public static boolean isAppInstalled(Context context, String packageName) {
try {
context.getPackageManager().getApplicationInfo(packageName, 0);
return true;
}
catch (PackageManager.NameNotFoundException e) {
return false;
}
}
I chose to put it in a helper class as a static utility. Usage example:
boolean whatsappFound = AndroidUtils.isAppInstalled(context, "com.whatsapp");
This answer shows how to get the app from the Play Store if the app is missing, though care needs to be taken on devices that don't have the Play Store.