I want to add a custom attribute / property into the manifest file, and be able to read it at run time. I want to do this so I can customize the app's behavior via these manifest properties. How can this be done?
Asked
Active
Viewed 2.2k times
2 Answers
78
You can add meta-data to your AndroidManifest.xml
file and then read that in your application.
Write the data like so:
<meta-data android:value="bar" android:name="foo"></meta-data>
And read the data like so:
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
Object value = (Object)ai.metaData.get("foo");
See http://developer.android.com/guide/topics/manifest/meta-data-element.html
-
2The calls here work perfectly. One thing worth mentioning if other users come across this is that you'll want to wrap this with try/catch PackageManager.NameNotFoundException (especially in Android Studio, this won't even compile without wrapping it). – Wes Winn Dec 03 '14 at 20:56
10
You can create an empty resource file in res/values and add strings and items (for bool or integer values) to it.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="foo">bar</string">
<item name="testint" type="integer">33</item>
<item name="testbool" type="bool">true</item>
</resources>
Alternatively you could simply use a Constants object in which you define your properties as final static variables.

nanoquack
- 949
- 2
- 9
- 26
-
1thanks, would you please show the code needed to read the value of foo from the resource file – inor Oct 30 '11 at 03:47
-
4should be getResources().getString(R.string.foo) getResources().getInteger(R.integer.testint) getResources.getBoolean(R.bool.testbool) see http://developer.android.com/guide/topics/resources/more-resources.html for more details – nanoquack Oct 30 '11 at 23:24
-
-
yes this is an alternative but if you have multi values folder like values-en, values-jp you must define your constants to all strings.xml files. same data in multiple files, I think this is disadvantage in many ways. – Phd. Burak Öztürk Feb 22 '16 at 01:12
-
I believe the drawback in the comment above can be relieved by using a base "values" folder with no localization suffix – ItsJason Mar 12 '19 at 00:13