不能setClassName开始新的意图不同封装的Android [英] Cannot start new Intent by setClassName with different package in Android
问题描述
我要动态地启动一个新的意图。因此 setClassName
似乎是最好的选择。
I want to start a new Intent dynamically. Therefore setClassName
seems the best choice.
首先,我定义在清单3活性
First, I define 3 activity in Manifest
<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);
和会得到这个异常:
And will get this exception:
Unable to find explicit activity class {com.example.pkg2.Act/com.example.pkg1.Act1}; have you declared this activity in your AndroidManifest.xml?
看起来,我们只能用 setClassName
来动态地启动新的活动,但在同一封装内。
It looks like we can only use setClassName
to dynamically start new Activity but within the same package.
任何想法来解决这个问题?所有帮助AP preciated。
Any idea to solve this issue? All help is appreciated.
推荐答案
setClassName采取包上下文作为第一个参数 setClassName(上下文packageContext,弦乐的className)
:
setClassName take a Package Context as first param 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" />
或你试试这个:
or you try this :
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);
}
这篇关于不能setClassName开始新的意图不同封装的Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!