将活动别名检查到目标活动中

gre*_*f82 3 android

我有一个名为 A 的活动。我想添加两个名为 B 和 C 的活动别名。是否可以知道 A 在代码中是否被称为 B 或 C?当它被称为 B 或 C 时,我想应用不同的行为。

0X0*_*gar 5

您可以为其中的每项提供一些附加信息<actvity-alias>ManifestActivityInfo在以下方面进行评估PackageManager

为了说明这一点,我们假设您想要TextView在目标中显示两个 sActivity并根据使用的别名设置内容。

在 中Manifest,您放置以下元素:

<activity
    android:name=".HalloActivity"
    android:label="@string/HalloDefault" >
</activity>
<activity-alias
    android:name=".SalutActivity"
    android:targetActivity=".HalloActivity"
    android:label="@string/SalutAlias">
    <meta-data android:name="LOCALE" android:value="fr" />
</activity-alias>
<activity-alias
    android:name=".HelloActivity"
    android:targetActivity=".HalloActivity"
    android:label="@string/HelloAlias">
    <meta-data android:name="LOCALE" android:value="en" />
</activity-alias>
Run Code Online (Sandbox Code Playgroud)

要使用别名,请Activity像这样启动:

Intent intent = new Intent();
String pName = getPackageName();
ComponentName componentName = new ComponentName(pName, pName + ".HelloActivity");
intent.setComponent(componentName);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

然后在HalloActivityonCreate()的 then 方法中,得到类似这样的内容:android:label<meta-data>

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hallo);

    String text;
    String label = "?";
    String locale = "de";
    int color;

    Intent intent = getIntent();
    PackageManager pm = getPackageManager();
    try
    {
        ActivityInfo ai = pm.getActivityInfo(intent.getComponent(), PackageManager.GET_META_DATA);

        label = getString(ai.labelRes);

        Bundle b = ai.metaData;

        if (b != null)
        {
            locale = b.getString("LOCALE");
            if (locale == null)
            {
                locale = "en";
            }
        }
    }
    catch (Exception ex)
    {
        Log.e(TAG, ex.getMessage());
    }

    switch(locale)
    {
        case "en":
            text = "hello world :)";
            color = Color.BLUE;
            break;
        case "fr":
            text = "salut tout le monde :D";
            color = Color.RED;
            break;
        default:
            text = "hallo zusammen ;)";
            color = Color.GREEN;
    }


    TextView tvHello = (TextView) findViewById(R.id.tvHello);
    tvHello.setText(text);
    tvHello.setTextColor(color);

    TextView tvLabel = (TextView) findViewById(R.id.tvLabel);
    tvLabel.setText(label);
}
Run Code Online (Sandbox Code Playgroud)

使用时很重要<activity-alias>(引自文档):

除 targetActivity 之外,属性都是活动属性的子集。对于子集中的属性,为目标设置的任何值都不会传递到别名。但是,对于不在子集中的属性,为目标活动设置的值也适用于别名。

<meta-data>文档中了解更多信息。