<meta-data android:name="weather" android:value="xxx"/>
使用第三方SDK,需要在APP应用内使用别的APP的整合包,如使用微信登录、某某地图等。
在java代码中,获取元数据信息的步骤分为下列三步:
例:从清单文件中获取元数据并显示到屏幕上
清单文件
- <activity
- android:name=".MetaDataActivity"
- android:exported="true">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- <meta-data android:name="weather" android:value="xxx"/>
- </activity>
xml文件
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
-
- <TextView
- android:id="@+id/tv_meta"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"/>
-
- </LinearLayout>
java类
- public class MetaDataActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_meta_data);
- TextView tv_meta = findViewById(R.id.tv_meta);
- //获取应用包管理器
- PackageManager pm = getPackageManager();
- try {
- //从应用包管理器中获取当前的活动信息
- ActivityInfo info = pm.getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);
- //获取活动附加的元数据信息
- Bundle bundle = info.metaData;
- String weather = bundle.getString("weather");
- tv_meta.setText(weather);
- } catch (PackageManager.NameNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
运行结果

元数据不仅能传递简单的字符串参数,还能传送更复杂的资源数据,如支付宝的快捷式菜单。

元数据的meta-data标签除了前面的name属性和value属性,还拥有resource属性,该属性可指定一个XML文件,表示元数据想要的复杂信息保存于XML数据之中。
利用元数据配置快捷菜单的步骤如下:
例:长按应用出现快捷菜单
清单文件AndroidManifest.xml
- <activity
- android:name=".ActStartActivity"
- android:exported="true">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- <meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts"/>
- </activity>
新建shortcuts.xml文件用于配置快捷菜单
- <resources xmlns:android="http://schemas.android.com/apk/res/android">
- <shortcut
- android:shortcutId="first"
- android:enabled="true"
- android:icon="@mipmap/ic_launcher"
- android:shortcutLongLabel="@string/first_long"
- android:shortcutShortLabel="@string/first_short">
- <!--文字太长则显示shotLabel ↑-->
- <!--点击选项跳转到的页面 ↓-->
- <intent
- android:action="android.intent.action.VIEW"
- android:targetPackage="com.example.chapter2"
- android:targetClass="com.example.chapter2.ActStartActivity"/>
- <categories android:name="android.shortcut.conversation"/>
- </shortcut>
- </resources>
运行结果:长按出现快捷菜单
