I need to write some util class by myself and I need the packagename of android app. While I found the packageManager which only can be used in Activity and so on that has c
you can get the package name of installed app:
ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
PackageManager pm = getApplicationContext().getPackageManager();
List<PackageInfo> packs = pm.getInstalledPackages(0);
and if you want to find the package name of your app:
context.getPackageName();
I have seen the following two ways to get the package name starting from a Context variable:
context.getPackageManager().getPackageInfo(context.getPackageName(), 0).packageName
and
context.getPackageName()
Won't they always give the same answer? Is one way preferable to use over the other in certain circumstances?
Here add this to your util class. It makes sure to handle different “flavors” and debug/release builds, as other answers do not:
@Nullable
public static String getApplicationPackageName(@NonNull Context context)
{
final PackageInfo packageInfo = getPackageInfo(context);
if (packageInfo.applicationInfo == null)
{
return null;
}
// Returns the correct “java” package name that was defined in your
// AndroidManifest.xml.
return packageInfo.applicationInfo.packageName;
}
// Convenience method for getting the applications package info.
@NonNull
private static PackageInfo getPackageInfo(@NonNull final Context context)
{
final PackageManager packageManager = context.getPackageManager();
try
{
return packageManager.getPackageInfo(context.getPackageName(), 0);
}
catch (final PackageManager.NameNotFoundException ignored)
{
//noinspection ConstantConditions: packageInfo should always be available for the embedding app.
return null;
}
}