Starting an Activity with Intent and SetClassName

2019-03-02 11:07发布

问题:

I am using the following code to move to another Activity :

Intent intent = new Intent();  
String test = "Navigate";  
intent.setClassName(this.context,test);  
intent.putExtra("params", params);  
((Activity) context).startActivity(intent);  

But I am unable to start the Navigate Activity. No exception is thrown. For the same, the folowing code works fine:

Intent intent = new Intent(this.context,Navigate.class);  
intent.putExtra("params", params); 
((Activity) context).startActivity(intent);    

Please tell me if any work around.

回答1:

You need the full classname, including the package:

String test = "your.package.here.Navigate";

(And the Activity defined in the Manifest, but as you can start it with Navigate.class I assume you have already done this).



回答2:

I would use the more explicit constructor: Intent (Context packageContext, Class<?> cls). From the docs:

[...] This provides a convenient way to create an intent that is intended to execute a hard-coded class name, rather than relying on the system to find an appropriate class for you [...]

This constructor internally calls the setComponent()-method, which is also called by your used setClassName()-method. But using the constructor spares you code-lines and makes the code more readable:

Intent i = new Intent(this, Navigate.class);
intent.putExtra("params", params);
this.startActivity(i);

Note that using this only works this way, when in an Activity, because the activity-class extends the Context-class.

Another advantage over hard-coding the package and class-names as a String is, that when you move a class to another package (or rename a package), you'll get compile-time errors, not runtime-errors.

Also, for this to work, you'll need to register the Activity in the Android Manifest.