
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.helloworld">
- <application
- android:allowBackup="true"
- android:icon="@mipmap/ic_launcher"
- android:label="@string/app_name"
- android:roundIcon="@mipmap/ic_launcher_round"
- android:supportsRtl="true">
- <activity
- android:name=".MainActivity"
- android:launchMode="standard"
- android:theme="@style/Theme.AppCompat.Light"
- android:exported="true">
- //添加在这里
- <meta-data android:name="slogan" android:value="hello world!" />
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
2.配置好了activity节点的meta-data标签,再回到Java代码获取元数据信息,获取步骤分为下列3步:
- 调用getPackageManager方法获得当前应用的包管理器。
- 调用包管理器的getActivityInfo方法获得当前活动的信息对象。
活动信息对象的 metaData 是 Bundle 包裹类型,调用包裹对象的 getString 即可获得指定名称的参数 值。
XML代码:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical"
- android:gravity="center"
- tools:context=".MainActivity">
- <Button
- android:id="@+id/request"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="发送"
- />
-
- <TextView
- android:id="@+id/t1"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:textColor="#000000"
- />
- </LinearLayout>
Java代码:
- import android.content.pm.ActivityInfo;
- import android.content.pm.PackageManager;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.TextView;
- import androidx.annotation.Nullable;
- import androidx.appcompat.app.AppCompatActivity;
-
-
- public class MainActivity extends AppCompatActivity{
- @Override
- protected void onCreate(@Nullable Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- TextView textView=findViewById(R.id.t1);
- findViewById(R.id.request).setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- try {
- PackageManager pa = getPackageManager(); //获取应用包管理器
- //从应用包管理器获取当前应用信息
- ActivityInfo act=pa.getActivityInfo(getComponentName(),PackageManager.GET_META_DATA);
- Bundle bundle=act.metaData; //获取活动附加的元数据信息
- String value=bundle.getString("slogan"); //从包裹中取出名为slogan的字符串
- textView.setText(value);
- } catch (PackageManager.NameNotFoundException e) {
- e.printStackTrace();
- }
- }
- });
- }
- }