get activityInfo metaData in onCreate method
Asked Answered
K

3

10

I need to retrieve a value from the AndroidManifest.xml file, stored as a meta data:

<meta-data android:value="3" android:name="myInterestingValue" />

In the onCreate method, I call the following method:

private Object getMetaData(String name) {
    try {
        ActivityInfo ai = getPackageManager().getActivityInfo(this.getComponentName(), PackageManager.GET_META_DATA);
        Bundle metaData = ai.metaData; 
        if(metaData == null) {
            debug("metaData is null. Unable to get meta data for " + name);
        }
        else {
            Object value = (Object)metaData.get(name);
            return value;
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

But the metaData is always null. Is it impossible to access the metaData in the onCreate method? i.e. The activity has not been fully initialized yet.

Kerbela answered 21/9, 2011 at 13:4 Comment(0)
A
27

You will need to use the flags GET_ACTIVITIES and GET_META_DATA.

ActivityInfo ai = getPackageManager()
        .getActivityInfo(this.getComponentName(), PackageManager.GET_META_DATA);
Abseil answered 10/11, 2011 at 4:18 Comment(1)
Thanks, this helped. You have a typo, should be : ActivityInfo app = getPackageManager().getActivityInfo( this.getComponentName(), PackageManager.GET_ACTIVITIES|PackageManager.GET_META_DATA);Bromide
P
1

If you are interested, android-metadata is a framework that makes it easier to get metadata from the Android manifest. The way you would get the meta-data above using android-metadata is:

int val = ManifestMetadata.get (context).getValue ("myInterestingValue", Integer.class);

Full disclosure: I'm the creator of android-metadata.

Postage answered 12/3, 2014 at 19:17 Comment(1)
Is it merged in androidannotations (github.com/excilys/androidannotations) framework ?Fowler
F
1

I've tried jasonj's answer but it doesn't work. To retrieve meta-data from manifest file, I must get the following code

ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
Bundle bundle = ai.metaData;

OR the Kotlin version:

val ai = packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA)
val bundel = ai?.metaData 
Fowler answered 1/8, 2014 at 9:3 Comment(1)
getApplicationInfo is used to get metadata from the <application> element. To get meta-data from <activity> element you have to use getActivityInfo as describedPlayful

© 2022 - 2024 — McMap. All rights reserved.