Performing Application Tasks with Activities Android

The Android Activity class ( is core to any Android application. Much of the time, you define and implement an Activity class for each screen in your application. For example, a simple game application might have the following five Activities, as shown in Figure:

  • A Startup or Splash screen: This activity serves as the primary entry point to the application. It displays the application name and version information and transitions to the Main menu after a short interval.
  • A Main Menu screen: This activity acts as a switch to drive the user to the core Activities of the application. Here the users must choose what they want to do within the application.
  • A Game Play screen: This activity is where the core game play occurs.
  • A High Scores screen: This activity might display game scores or settings.
  • A Help/About screen: This activity might display the information the user might need to play the game.

A simple game with five activities.

A simple game with five activities.

The Lifecycle of an Android Activity

Android applications can be multi-process, and the Android operating system allows multiple applications to run concurrently, provided memory and processing power is available. Applications can have background processes, and applications can be interrupted and paused when events such as phone calls occur. There can be only one active application visible to the user at a time—specifically, a single application Activity is in the foreground at any given time.

The Android operating system keeps track of all Activity objects running by placing them on an Activity stack. When a new Activity starts, the Activity on the top of the stack (the current foreground Activity) pauses, and the new Activity pushes onto the top of the stack. When that Activity finishes, that Activity is removed from the activity stack, and the previous Activity in the stack resumes.

The Activity stack.

The Activity stack

Android applications are responsible for managing their state and their memory, resources, and data. They must pause and resume seamlessly. Understanding the different states within the Activity lifecycle is the first step to designing and developing robust Android applications.

Using Activity Callbacks to Manage Application State and Resources

Different important state changes within the Activity lifecycle are punctuated by a series of important method callbacks. These callbacks are shown in Figure.

Here are the method stubs for the most important callbacks of the Activity class:

The lifecycle of an Android Activity.

The lifecycle of an Android Activity

Now let’s look at each of these callback methods, when they are called, and what they are used for.

Initializing Static Activity Data in onCreate()

When an Activity first starts, the onCreate() method is called. The onCreate() method has a single parameter, a Bundle, which is null if this is a newly started Activity. If this Activity was killed for memory reasons and is now restarted, the Bundle contains the previous state information for this Activity so that it can reinitiate. It is appropriate to perform any setup, such as layout and data binding, in the onCreate() method. This includes calls to the setContentView() method.

Initializing and Retrieving Activity Data in onResume()

When the Activity reaches the top of the activity stack and becomes the foreground process, the onResume() method is called.Although the Activity might not be visible yet to the user, this is the most appropriate place to retrieve any instances to resources (exclusive or otherwise) that the Activity needs to run. Often, these resources are the most process-intensive, so we only keep these around while the Activity is in the foreground.

Stopping, Saving, and Releasing Activity Data in onPause()

When another Activity moves to the top of the activity stack, the current Activity is informed that it is being pushed down the activity stack by way of the onPause() method.

Here, the Activity should stop any audio, video, and animations it started in the onResume() method.This is also where you must deactivate resources such as database Cursor objects if you have opted to manage them manually, as opposed to having them managed automatically.

The onPause() method can also be the last chance for the Activity to clean up and release any resources it does not need while in the background. You need to save any uncommit- ted data here, in case your application does not resume.

The Activity can also save state information to Activity-specific preferences, or application wide preferences.

The Activity needs to perform anything in the onPause() method quickly. The new fore ground Activity is not started until the onPause() method returns.

Avoiding Activity Objects Being Killed

Under low-memory conditions, the Android operating system can kill the process for any Activity that has been paused, stopped, or destroyed. This essentially means that any Activity not in the foreground is subject to a possible shutdown.

If the Activity is killed after onPause(), the onStop() and onDestroy() methods might not be called.The more resources released by an Activity in the onPause() method, the less likely the Activity is to be killed while in the background.

The act of killing an Activity does not remove it from the activity stack. Instead, the Activity state is saved into a Bundle object, assuming the Activity implements and uses on Save Instance State() for custom data, though some View data is automatically saved. When the user returns to the Activity later, the onCreate() method is called again, this time with a valid Bundle object as the parameter.

Saving Activity State into a Bundle with onSaveInstanceState()

If an Activity is vulnerable to being killed by the Android operating system due to low memory, the Activity can save state information to a Bundle object using the on Save Instance State() callback method. This call is not guaranteed under all circumstances, so use the onPause() method for essential data commits.

When this Activity is returned to later, this Bundle is passed into the onCreate() method, allowing the Activity to return to the exact state it was in when the Activity paused. You can also read Bundle information after the onStart() callback method using the on Restore Instance State() call back.

Destroy Static Activity Data in onDestroy()

When an Activity is being destroyed, the onDestroy() method is called. The onDestroy() method is called for one of two reasons: The Activity has completed its lifecycle voluntarily, or the Activity is being killed by the Android operating system because it needs the resources.

Managing Activity Transitions with Intents

In the course of the lifetime of an Android application, the user might transition between a number of different Activity instances. At times, there might be multiple Activity instances on the activity stack. Developers need to pay attention to the lifecycle of each Activity during these transitions.

Some Activity instances—such as the application splash/startup screen—are shown and then permanently discarded when the Main menu screen Activity takes over. The user cannot return to the splash screen Activity without re-launching the application.

Other Activity transitions are temporary, such as a child Activity displaying a dialog box, and then returning to the original Activity (which was paused on the activity stack and now resumes). In this case, the parent Activity launches the child Activity and expects a result.

Transitioning Between Activities with Intents

As previously mentioned,Android applications can have multiple entry points. There is no main() function, such as you find in iPhone development. Instead, a specific Activity can be designated as the main Activity to launch by default within the Android Manifest.xml file; we talk more about this file in Chapter “Defining Your Application Using the Android Manifest File.”

Other Activities might be designated to launch under specific circumstances. For example, a music application might designate a generic Activity to launch by default from the Application menu, but also define specific alternative entry point Activities for accessing specific music playlists by playlist ID or artists by name.

Launching a New Activity by Class Name

You can start activities in several ways. The simplest method is to use the Application Context object to call the startActivity() method, which takes a single parameter, an Intent.

An Intent (android.content.Intent) is an asynchronous message mechanism used by the Android operating system to match task requests with the appropriate Activity or Service (launching it, if necessary) and to dispatch broadcast Intents events to the system at large.

For now, though, we focus on Intents and how they are used with Activities. The following line of code calls the startActivity() method with an explicit Intent. This Intent requests the launch of the target Activity named My Draw Activity by its class. This class is implemented elsewhere within the package.

This line of code might be sufficient for some applications, which simply transition from one Activity to the next. However, you can use the Intent mechanism in a much more robust manner. For example, you can use the Intent structure to pass data between Activities.

Creating Intents with Action and Data

You’ve seen the simplest case to use an Intent to launch a class by name. Intents need not specify the component or class they want to launch explicitly. Instead, you can create an Intent Filter and register it within the Android Manifest file. The Android operating system attempts to resolve the Intent requirements and launch the appropriate Activity based on the filter criteria.

The guts of the Intent object are composed of two main parts: the action to be performed and the data to be acted upon.You can also specify action/data pairs using Intent Action types and Uri objects.As you saw in Chapter “Writing Your First Android Application,” a Uri object represents a string that gives the location and name of an object. Therefore, an Intent is basically saying “do this” (the action) to “that” (the Uri describing what resource to do the action to).

The most common action types are defined in the Intent class, including ACTION_MAIN (describes the main entry point of an Activity) and ACTION_EDIT (used in conjunction with a Uri to the data edited).You also find Action types that generate integration points with Activities in other applications, such as the Browser or Phone Dialer.

Launching an Activity Belonging to Another Application

Initially, your application might be starting only Activities defined within its own package. However, with the appropriate permissions, applications might also launch external Activities within other applications. For example, a Customer Relationship Management (CRM) application might launch the Contacts application to browse the Contact database, choose a specific contact, and return that Contact’s unique identifier to the CRM application for use.

Here is an example of how to create a simple Intent with a predefined Action (ACTION _DIAL) to launch the Phone Dialer with a specific phone number to dial in the form of a simple Uri object:

You can find a list of commonly used Google application Intents. Also available is the developer managed Registry of Intents protocols at OpenIntents, which has a growing list of Intents available from third-party applications and those within the Android SDK.

Passing Additional Information Using Intents

You can also include additional data in an Intent.The Extras property of an Intent is stored in a Bundle object.The Intent class also has a number of helper methods for getting and setting name/value pairs for many common datatypes.

For example, the following Intent includes two extra pieces of information—a string value and a boolean:

Organizing Activities and Intents in Your Application Using Menus
As previously mentioned, your application likely has a number of screens, each with its own Activity. There is a close relationship between menus, Activities, and Intents. You often see a menu used in two different ways with Activities and Intents:

  • Main Menu: Acts as a switch in which each menu item launches a different Activity in your application. For instance, menu items for launching the Play Game Activity, the High Scores Activity, and the Help Activity.
  • Drill-Down: Acts as a directory in which each menu item launches the same Activity, but each item passes in different data as part of the Intent (for example, a menu of all database records). Choosing a specific item might launch the Edit Record Activity, passing in that particular item’s unique identifier.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Android Topics