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
Solution 1:
setClassName take a Package Context as first param setClassName(Context packageContext, String className)
:
Intentintent=newIntent();
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
<activityandroid:name="com.example.pkg2.Act" /><activityandroid:name="com.example.pkg1.Act1" /><activityandroid:name="com.example.pkg1.Act2" />
or you try this :
if(index == 0) {
Intentintent=newIntent(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(newComponentName("com.example.pkg1", "com.example.pkg1.Act1"));
getApplicationContext().startActivity(intent);
} else {
Intentintent=newIntent(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(newComponentName("com.example.pkg1", "com.example.pkg1.Act2"));
getApplicationContext().startActivity(intent);
}
Solution 2:
The first param is the applicationId located in the build.gradle file
The second param is full path to of the class with its package. for example: intentObj.setClassName("applicatioId", "com.youCompany.yourAppName.YourClassName")
Solution 3:
You can also launch Activities in this manner. Try this
Intentintent=newIntent();
Class<?> activityClass = Class.forName("your.application.package.name." + NameOfClassToOpen);
intent.setClass(this, activityClass);
And in order to use setClassName. You should supply it with packageName and its class path too like
intent.setClassName("your.application.package.name", "your.application.package.name.activityClass");
Solution 4:
Follow the syntax to write setClassName() method:
setClassName( pkgName, className )
Solution 5:
You can use the following method to create the intent in the package context:
Intent intent = newIntent(this, MyActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
This way you keep on generic code.
HTH
Post a Comment for "Cannot Start New Intent By Setclassname With Different Package In Android"