Last Updated: February 25, 2016
· adnaan

Android: Meta-Data

Using "strings" attribute is a good way to get string resources in activities/fragments. Though sometimes you need context wide configuration information which is readily available on application start-up. One of the use cases is to get third-party api-keys. We can use "meta-data" to accomplish that. Here is some pseudo-code:

android:value="myapkikeyvalue" />

Retrieving the api-key:

 public static final String METADATA_KEY_API_KEY =   "";

final PackageManager pm = context.getPackageManager();
        ApplicationInfo appInfo;
        try {
            appInfo = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        } catch (final NameNotFoundException e) {
            throw new RuntimeException(e);

        final Bundle metadata = appInfo.metaData;
        mKey = metadata.getString(METADATA_KEY_API_KEY);