How can I get package name in android?

后端 未结 9 1311
耶瑟儿~
耶瑟儿~ 2020-12-11 05:14

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

9条回答
  •  醉梦人生
    2020-12-11 05:46

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

提交回复
热议问题