转:http://www.2cto.com/kf/201208/151123.html
Android开发中我们常常需要知道,当前应用的版本信息。可以进行自动升级判断。扩展自定义数据 meta-data, 这些数据都在AndroidManifest.xml .我们如何获取这些信息呢?下来示例如何读取这些数据。1 版本信息、应用名称2 Appliction 的Meta-data3 Activity中的Meta-dataAndroidManifest.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:Test116:37:54.442: I/System.out(10213): versionName:1.016:37:54.442: I/System.out(10213): tel:cdma-1336635037716:37:54.442: I/System.out(10213): channel:eben16:37:54.452: I/System.out(10213): name:自强不息16:37:54.452: I/System.out(10213): city:北京