Read the meta-data data of the AndroidManifest file

Meta-data tags can be added to AndroidManifest.xml to define some configuration data, which can be read in the app.
The meta-data tag defines a set of key-value pairs, namely name and value. Although meta-data does not define the attributes of the data type, in fact meta-data data has a data type, and this type is automatically derived from the value data. The commonly used types are as follows: pure numbers belong to the int type, characters with non-digits belong to the String type, and if the string is true or false, it belongs to the boolean type.

Examples are as follows:
Defined in AndroidManifest.xml:

<application>
<meta-data
    android:name="test_int"
    android:value="2147483647" />
<meta-data
    android:name="test_string"
    android:value="abcdefg" />
<meta-data
    android:name="test_boolean"
    android:value="true" />
</application>

Analysis in java:

private void getMeta() {
    try {
        ApplicationInfo appInfo = context.getPackageManager()
                .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        int testInt = appInfo.metaData.getInt("test_int");
        String testString = appInfo.metaData.getString("test_string", "");
        boolean testBoolean = appInfo.metaData.getBoolean("test_boolean", false);
        Log.d(TAG, "getMeta testInt=" + testInt + ",testString=" + testString + ",testBoolean=" + testBoolean);
    } catch (Exception x) {
        Log.e(TAG, "getMeta error=" + x);
    }
}

Note:
1. Meta-data data has data types. If the data is not fetched according to the correct data type, the expected data will not be obtained.
2. When defining data for some data types, you need to pay special attention to the value range of the data. For example, the int type has a maximum value of 2^31-1, which is 2147483647. If the defined data is greater than this value, the expected data will not be obtained. How to get data beyond the range of values? One way is to add a prefix string to convert it to a string type, read it according to the string type during parsing, and then remove the prefix to get the expected data.
3. When defining boolean data, you can define value data while ignoring case. For example, true, True, TRUE, false, False, and FALSE can all be parsed correctly.
4. Meta-data data can be defined in the <application>, <activity>, <activity-alias>, <service>, <receiver>, <provider> tags in AndroidManifest.xml. The examples in this article are in the most commonly used <application >In the label. Of course, the analysis method for each situation is different, so this article will not introduce it in detail.

Guess you like

Origin blog.csdn.net/chenzhengfeng/article/details/110093807