AndroidManifest元数据在java代码的顶级列表中

时间:2015-04-30 08:47:32

标签: java metadata android-manifest

如何在java代码中获取AndroidManifest的元数据。我不需要应用程序的元数据,但这些来自清单xml中的更高级别。我的AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.aaa.bbb">


   <application
    ...
    <activity
      ....
    </activity>
   </application>

<meta-data android:name="mykey" android:value="myvalue"/>

</manifest>

我需要在我的java代码中提取mykey的值。

2 个答案:

答案 0 :(得分:1)

我正在使用此代码。希望它有所帮助。

private String getStringFromManifest(String whatToGet) {
        String valueObtained = null;
        try {
            Bundle data = getManifestData();
            valueObtained = data.getString(whatToGet, null);
            if (valueObtained == null) {
                log.error("Value for '" + whatToGet + "' not found in AndroidManifest");
            }
        } catch (PackageManager.NameNotFoundException e) {
            log.error("Error in configuration");
        }
        return valueObtained;
    }


private Bundle getManifestData() throws PackageManager.NameNotFoundException {
    ComponentName myActivity = new ComponentName(this, this.getClass());
    return getPackageManager().getActivityInfo(myActivity, PackageManager.GET_META_DATA).metaData;
}

答案 1 :(得分:0)

您必须提供一些代码,以便了解您的尝试...

无论如何,标准将是这样的:

File xml_file=new File("manifest.xml");
if (xml_file.isFile() && xml_file.canRead()) {
    Document doc = builder.parse(xml_file);
    Element root = doc.getDocumentElement();
    NodeList nodel = root.getChildNodes();
    Node node = nodel.item(a);
    if(node instanceof Element) {
        // this is the meta-data element
        Element data = ((Element)node).getAttribute("meta-data");
        // if you want the attributes
        String key = data.getNamedItem("android:name").getNodeValue();
    }
}