How can I get package name in android?

后端 未结 9 1313
耶瑟儿~
耶瑟儿~ 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:43

    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();
    
    0 讨论(0)
  • 2020-12-11 05:44

    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?

    0 讨论(0)
  • 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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题