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
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;
}
}