Cannot start new Intent by setClassName with diffe

2019-01-19 15:45发布

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.

8条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-19 16:11

Use this code and you'll be fine.

Intent intent = new Intent();
String resourcePackageName = getResources().getResourcePackageName(R.string.some_defined_resource);
intent.setClassName(getApplicationContext().getPackageName(),resourcePackageName + ".SubPackageName[/if any/].ClassName");
startActivity(intent);
查看更多
Luminary・发光体
3楼-- · 2019-01-19 16:17

You can use the following method to create the intent in the package context:

    Intent intent = new Intent(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

查看更多
成全新的幸福
4楼-- · 2019-01-19 16:25

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

查看更多
仙女界的扛把子
5楼-- · 2019-01-19 16:25

You can also launch Activities in this manner. Try this

Intent intent = new Intent();
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");
查看更多
够拽才男人
6楼-- · 2019-01-19 16:27

intent.setClassName(packageName, className);

where
packageName - The name of the package implementing the desired component, i.e. the package where the caller belongs to.
className - fully qualified name of the class [from different package]

Calling from com.example.pkg2.Act:

intent.setClassName("com.example.pkg2", "com.example.pkg1.Act1");
查看更多
甜甜的少女心
7楼-- · 2019-01-19 16:28

Follow the syntax to write setClassName() method:

 setClassName( pkgName, className ) 
查看更多
登录 后发表回答