14

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 ?

1

2 Answers 2

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) {}
Sign up to request clarification or add additional context in comments.

1 Comment

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
2

From your "main" Activity class:

String package = this.getClass().getPackage().getName();

3 Comments

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)
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
This will clear things up. stackoverflow.com/questions/6589797/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.