Wednesday, September 25, 2013

Android: Access meta-data defined AndroidManifest

Image by Gideon Burton
I want to share another tip for Android with you. Sometimes it is necessary to have access some configuration data from your app and there are of course multiple solutions to store such data.
You could for example just use a Java Class defining constants that you reuse everywhere or you could use string/integer/… resources and just load them but I would like to show you another possibility you have.
Maybe it is not the best solution but I at least wanted to show you how it's done ;).

Manifest meta-data

Define meta-data

Let's start with the data. In order to provide meta-data in the AndroidManifest, just add a <meta-data/> tag as a child of <application/> like this:
 <application […]>
    […]
    <meta-data android:name="yourkey" android:value="the value" />
</application>
The value can basically be anything you want as long as it's a string, boolean, integer, float or color – either as a direct value or a typical Android reference ;). As an alternative to the android:value attribute you can use android:resource to add a value reference. The big difference is that with value, the key will return the actual content of the value, whereas the reference will only store the (int-)ID of the resource.
Hint: when you want to add a long instead of an int, you will either have to use a string reference or add "\ " (without the quotes) in order for Android to interpret it as a string (and for you to be able to parse it using Long.valueOf).

Read meta-data

The second part of course includes reading meta-data. This is quite simple, as you can just use the following snipped:
try {
    String pkgName = _context.getPackageName();
    Bundle info = _context.getPackageManager().getApplicationInfo(pkgName, PackageManager.GET_META_DATA).metaData;
    return info.getString("yourkey");
} catch (NameNotFoundException e) {
    // TODO
}
Really easy as you will just receive a Bundle and get use the known methods for retrieving values from Bundles – just replace the call to getString as needed.

Who uses it?

When using the newest Facebook SDK for Android, you will also encounter this solution – though you won't have to access the meta-data yourself.
And of course Google/Android uses it too. For some features of the compatibility library to work correctly (the up-navigation pattern), you also have to add meta-data tags, though not as a child of the application but of the activity tag.

Labels: , , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home