Launching Activities

There are a number of ways to launch an activity, including the following:

► Designating a launch activity in the manifest file

► Launching an activity using the application context

► Launching a child activity from a parent activity for a result

Designating a Launch Activity in the Manifest File

Each Android application must designate a default activity within the Android manifest file. If you inspect the manifest file of the Droidl project, you will notice that DroidActivity is designated as the default activity.

Did you Know?

Other Activity classes might be designated to launch under specific circumstances. You manage these secondary entry points by configuring the Android manifest file with custom filters.

In Chippy's Revenge, SplashActivity would be the most logical activity to launch by default.

Launching Activities Using the Application Context

The most common way to launch an activity is to use the startActivity() method of the application context. This method takes one parameter, called an intent. We will talk more about the intent in a moment, but for now, let's look at a simple startActivity() call.

The following code calls the startActivity() method with an explicit intent: startActivity(new Intent(getApplicationContext(), MenuActivity.class));

This intent requests the launch of the target activity, named MenuActivity, by its class. This class must be implemented elsewhere within the package.

Because the MenuActivity class is defined within this application's package, it must be registered as an activity within the Android manifest file. In fact, you could use this method to launch every activity in your theoretical game application; however, this is just one way to launch an activity.

Launching an Activity for a Result

Sometimes an activity wants to launch a related activity and get the result, instead of launching an entirely independent activity. In this case, you can use the

Activity.startActivityForResult() method. The result will be returned in the Intent parameter of the calling activity's onActivityResult() method. We will talk more about how to pass data using an Intent parameter in a moment.

0 0

Post a comment