gpt4 book ai didi

android - 无法通过 setClassName 在 Android 中使用不同的包启动新的 Intent

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:22:18 25 4
gpt4 key购买 nike

我想动态地启动一个新的 Intent。因此 setClassName 似乎是最好的选择。

首先,我在Manifest中定义了3个activity

<activity android:name="com.example.pkg2.Act" />
<activity android:name="com.example.pkg1.Act1" />
<activity android:name="com.example.pkg1.Act2" />

来自com.example.pkg2.Act:

Intent intent = new Intent();
if(index == 0) intent.setClassName(Act.this, "com.example.pkg1.Act1");
else intent.setClassName(Act.this, "com.example.pkg1.Act2");
startActivity(intent);

并且会得到这个异常:

Unable to find explicit activity class {com.example.pkg2.Act/com.example.pkg1.Act1}; have you declared this activity in your AndroidManifest.xml?

看起来我们只能使用 setClassName 来动态启动新的 Activity 但在同一个包中。

有解决这个问题的想法吗?感谢所有帮助。

最佳答案

setClassName 以一个包上下文作为第一个参数setClassName(Context packageContext, String className):

Intent intent = new Intent();
if(index == 0) {
intent.setClassName("com.example.pkg1", "com.example.pkg1.Act1");
} else {
intent.setClassName("com.example.pkg1", "com.example.pkg1.Act2");
startActivity(intent);
}

<activity android:name="com.example.pkg2.Act" />
<activity android:name="com.example.pkg1.Act1" />
<activity android:name="com.example.pkg1.Act2" />

或者你试试这个:

if(index == 0) {
Intent intent = new Intent(Intent.ACTION_MAIN)
.addCategory(intent.CATEGORY_LAUNCHER)
.setClassName("com.example.pkg1", "com.example.pkg1.Act1")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_FROM_BACKGROUND)
.setComponent(new ComponentName("com.example.pkg1", "com.example.pkg1.Act1"));
getApplicationContext().startActivity(intent);
} else {
Intent intent = new Intent(Intent.ACTION_MAIN)
.addCategory(intent.CATEGORY_LAUNCHER)
.setClassName("com.example.pkg1", "com.example.pkg1.Act2")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.addFlags(Intent.FLAG_FROM_BACKGROUND)
.setComponent(new ComponentName("com.example.pkg1", "com.example.pkg1.Act2"));
getApplicationContext().startActivity(intent);
}

关于android - 无法通过 setClassName 在 Android 中使用不同的包启动新的 Intent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9923602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com