Android 之读取元素中的数据

众所周知, 每个组件都有<meta-data>元素, 用于接收一些外部数据(eg: appKey), 那其中的值应该怎么读取呢.
引用
1> Application

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="application_meta_data"
            android:value="application_meta_data_value" />  <!--可以关联资源ID, 支持多种数据类型 -->

ApplicationInfo info = null;    
     try {
         info = getPackageManager()
                   .getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
     } catch (NameNotFoundException e) {
         e.printStackTrace();
     }
Log.v(TAG, "application meta data value:" + info.metaData.getString("application_meta_data"));

引用
2> Activity

<activity
        android:name="fyc.app.testandroid.MainActivity" >
        <meta-data
            android:name="activity_meta_data"
            android:value="activity_meta_data_value" />
</activity>

ActivityInfo info = null;        
    try {
        info = getPackageManager()
                 .getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
Log.v(TAG, "activity meta data value:" + info.metaData.getString("activity_meta_data"));

引用
3> Service

<service android:name="fyc.app.testandroid.MyService" >
            <meta-data
                android:name="service_meta_data"
                android:value="service_meta_data_value" />
</service>

ServiceInfo info = null;
        
    try {
        info = getPackageManager()
                .getServiceInfo(new ComponentName(this, MyService.class), PackageManager.GET_META_DATA);  //如果在当前组件获取直接使用getcomponentName()
    } catch (NameNotFoundException e) {
            e.printStackTrace();
    }
Log.v(TAG, "service meta data value:" + info.metaData.getString("service_meta_data"));


引用
4> BroadcastReceiver

<receiver android:name="fyc.app.testandroid.MyReceiver" >
        <meta-data
                android:name="receiver_meta_data"
                android:value="receiver_meta_data_value" />
</receiver>

ActivityInfo info = null;
        
    try {
        info = getPackageManager()
                .getReceiverInfo(new ComponentName(this, MyReceiver.class), PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
Log.v(TAG, "receiver meta data value:" + info.metaData.getString("receiver_meta_data"));


Logcat输出信息

11:11:46.733: V/MainActivity(571): application meta data value:application_meta_data_value
11:11:46.733: V/MainActivity(571): activity meta data value:activity_meta_data_value
11:11:46.763: V/MainActivity(571): service meta data value:service_meta_data_value
11:11:46.783: V/MainActivity(571): receiver meta data value:receiver_meta_data_value
官方介绍

http://developer.android.com/guide/topics/manifest/meta-data-element.html


你可能感兴趣的:(android)