Android之读取 AndroidManifest.xml 中的数据

时间:2021-08-01 07:16:14

转:http://www.2cto.com/kf/201208/151123.html

下来示例如何读取这些数据。

1 版本信息、应用名称

2 Appliction 的Meta-data

3 Activity中的Meta-data

AndroidManifest.xml中的定义如下:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hpc.cai.test01"
android:versionCode="1"
android:versionName="1.0" >
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<meta-data
android:name="tel"
android:value="cdma-13366350377" >
</meta-data>
<meta-data
android:name="channel"
android:value="eben" />
<activity
android:name="hpc.cai.test.Test1Activity"
android:label="@string/app_name" >
<meta-data
android:name="name"
android:value="自强不息" >
</meta-data>
<meta-data
android:name="city"
android:value="北京" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

java 代码:

 /**
* activity MetaData读取
*/
private void testActivityMetaData() {
ActivityInfo info;
try {
info = getPackageManager().getActivityInfo(getComponentName(),
PackageManager.GET_META_DATA);
String msg = info.metaData.getString("name");
System.out.println("name:" + msg);
msg = info.metaData.getString("city");
System.out.println("city:" + msg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* appliction MetaData读取
*/
private void testApplicationMetaData() {
ApplicationInfo info;
try {
info = this.getPackageManager().getApplicationInfo(
getPackageName(), PackageManager.GET_META_DATA);
String msg = info.metaData.getString("tel");
System.out.println("tel:" + msg);
msg = info.metaData.getString("channel");
System.out.println("channel:" + msg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 测试版本信息
*/www.2cto.com
private void getVersion(){
PackageInfo pkg;
try {
pkg = getPackageManager().getPackageInfo(getApplication().getPackageName(), 0);
String appName = pkg.applicationInfo.loadLabel(getPackageManager()).toString();
String versionName = pkg.versionName;
System.out.println("appName:" + appName);
System.out.println("versionName:" + versionName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

输出如下:

16:37:54.442: I/System.out(10213): appName:Test1
16:37:54.442: I/System.out(10213): versionName:1.0
16:37:54.442: I/System.out(10213): tel:cdma-13366350377
16:37:54.442: I/System.out(10213): channel:eben
16:37:54.452: I/System.out(10213): name:自强不息
16:37:54.452: I/System.out(10213): city:北京