Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot start new Intent by setClassName with different package in Android

I want to start a new Intent dynamically. Therefore setClassName seems the best choice.

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" />

From 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?

It looks like we can only use setClassName to dynamically start new Activity but within the same package.

Any idea to solve this issue? All help is appreciated.

like image 283
anticafe Avatar asked Mar 29 '12 10:03

anticafe


1 Answers

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);
}

and in

<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);
}
like image 198
ρяσѕρєя K Avatar answered Nov 15 '22 23:11

ρяσѕρєя K