13

This should be simple but I can't find any info on this...

I simply want to read the package value in the android manifest...

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="THIS"

the reason is simple I have to call context.getResources().getIdentifier(...) and I need the package.

since this code will be reused in other apps I want to make it fool proof when I export it and therefore not have to change the value each time.

anybody knows how to do this ?

Jason Rogers
  • 19,194
  • 27
  • 79
  • 112

2 Answers2

18

Within an Activity, you can simply call getPackageName(). If you should happen to need additional data from the manifest, you can use the PackageInfo class: http://developer.android.com/reference/android/content/pm/PackageInfo.html

Example of setting a TextView to your app version:

    try {
        PackageManager pm = getPackageManager();
        PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(), 0);
        TextView version = (TextView) findViewById(R.id.version);
        version.setText(packageInfo.versionName);
    } catch (NameNotFoundException e) {}
sealskej
  • 7,281
  • 12
  • 53
  • 64
Ian G. Clifton
  • 9,349
  • 2
  • 33
  • 34
  • 2
    this seams to not be completely correct, as packageInfo.versionName does return the applicationId defined in the gradle file and not the package attribute in your manifest. As in most cases this is the same it will work fine, but when you are working with buildFlavors which change your applicationId this will no longer work. I dind't find any solution to this either but accessing the package attribtue through the `R`-class. Namely the package-attribute affects only the package name for the `R`-class and not the applicationId neither your normal class packages – da_berni Sep 15 '16 at 15:24
2

From your "main" Activity class:

String package = this.getClass().getPackage().getName();
Tyler
  • 21,762
  • 11
  • 61
  • 90
  • 7
    Its worth noting that this will only work if your main activity is in a package with the same name as the manifest package (and not, for example a sub package) – Richard Tingle Jul 15 '14 at 17:51
  • the package of the class must not match the package defined in the manifest, so this isn't correct, although in most cases this will work – da_berni Sep 08 '16 at 18:23
  • This will clear things up. https://stackoverflow.com/questions/6589797/how-to-get-package-name-from-anywhere/51479130#51479130 – user1506104 Jul 24 '18 at 04:26