Calling Activities from different package

2019-08-10 20:12发布

问题:

I have two activities from two different packages, I wish to call an activity in Package2 from package1 To do so i used the following,

Intent intentDeviceTest = new Intent();                
intentDeviceTest.setComponent(new ComponentName("chat.client.gui","chat.client.gui.MainActivity"));
startActivity(intentDeviceTest);

This shows an error that the activity is not found, add this to manifest.

But it works fine when i call it in this way,

Intent intentDeviceTest = new Intent(HomeActivity.this,MainActivity.class);      
startActivity(intentDeviceTest);

Whats the mistake in the above method!

回答1:

I always use the second form in my apps. It is simpler, clearer and shorter.

// Assumes that this is done from within an Activity
Intent intent = new Intent(this, AnotherActivity.class);  
startActivity(intent);

But I think the problem with the first form is that you specified the package again in the second parameter. You only need the class name:

Intent intentDeviceTest = new Intent();                
intentDeviceTest.setComponent(new ComponentName("chat.client.gui", "MainActivity"));
startActivity(intentDeviceTest);

Look at the first constructor in this for a reference: http://developer.android.com/reference/android/content/ComponentName.html