Using Components to Directly Invoke an Activity

You've seen a couple of ways to start an activity using intents. You saw an explicit action start an activity, and you saw a generic action start an activity with the help of a data URI. Android also provides a more direct way to start an activity: you can specify the activity's ComponentName, which is an abstraction around an object's package name and class name. There are a number of methods available on the Intent class to specify a component:

setComponent(ComponentName name);

setClassName(String packageName, String classNameInThatPackage); setClassName(Context context, String classNameInThatContext); setClass(Context context, Class classObjectInThatContext);

Ultimately, they are all shortcuts for calling one method:

setComponent(ComponentName name);

ComponentName wraps a package name and a class name together. For example, the following code invokes the contacts activity that ships with the emulator:

Intent intent = new Intent(); intent.setComponent(new ComponentName( "" ,""); startActivity(intent)

Notice that the package name and the class name are fully qualified, and are used in turn to construct the ComponentName before passing to the Intent class.

You can also use the class name directly without constructing a ComponentName. Consider the BasicViewActivity code snippet again:

public class BasicViewActivity extends Activity {

^Override public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState); setContentView(R.layout.some-view);

Given this, you can use the following code to start this activity:

Intent directIntent = new Intent(activity, BasicViewActivity.class); activity.start(directIntent);

If you want any type of intent to start an activity, however, you should register the activity in the Android.Manifest.xml file like this:

<activity android:name="BasicViewActivity" android:label="Test Activity">

No intent-filters are necessary for invoking an activity directly through its class name or component name.

0 0

Post a comment