Android Components – The Activity

This blog post will give you an introduction to Android Application Components and detailed description on one of the component i.e. Activity

Basically we have five major components that are used to build an application in android. These components are defined as Objects in Android SDK with some methods which can be used by an application. The developers only need to extend and use these classes and objects. The main Application components are listed below:

  • Activities
  • Services
  • Content Providers
  • Broadcast Receivers
  • Intents

thumb

You will learn how to build your application with these components as you read the tutorial and as you grow up in android development. Today in this tutorial, I will be giving you full description on first basic component i. e. Activity.

The “Activity”

activity1

Activity is a user interface screen in an Android Application where visual elements called Views or Widgets can be placed and the user can perform various actions by interacting with it.

An application can have more than one Activity and every Activity works independently, however can be connected to each other and must be defined in your application’s manifest file. Every Activity in Android will be subclass of Activity class defined in Android SDK.

In Other ways you can say that Activity is the

  • Basic component of most applications.
  • Most applications have several activities that start each other as needed.
  • Each is implemented as a subclass of the base Activity class.
  • Each activity has a default window to draw in (although it may prompt for dialogs or notifications).
  • The content of the window is a view or a group of views (derived from View or ViewGroup).
  • Example of views: buttons, text fields, scroll bars, menu items, check boxes, etc.
  • View (Group) made visible via Activity.setContentView() method.

Check the image below:

activity2

These are some native activities from Android 2.x such as Contact, dial-er etc which user can extent into his/her application and use as per the need.

Android keeps navigation history of activities user has visited which is called Activity Stack. It helps to display previous activity while pressing back button. User can not go further than the last visit of home activity.

activity3

You might have been heard the word task many times in programming world.  Task is a sequence of activities which can hold activities from several apps. Here in the above picture Activity that starts the task is called root activity. (Usually started from home screen)

A new task is started when new app is launched also it can be started on certain new activities.

activity4

Proceeding further we will discuss about the activity life cycle. The figure below shows various states of activity life cycle and their description.

activity5

Created and Started: These states tell user that the activity has been created and has visible to user. The system very quickly moves from these states to next state.

Resumed: This state tells the user that app is foreground and the user can interact with it.

Paused: This state tells that activity is partially obscures by another activity.

Stopped: This states means activity is not visible. It might be in the background; all the variables and members are retained but cannot execute the code.

Destroyed: This states means activity is no more visible and is out from the stack.

The methods related to these state are listed below:

onCreate() –  Creates the user Interface.

onStart()When activity is visible to user.

onResume() –  Activity is visible again, can initialize fields, register listeners and bind to services.

onPause() –  Activity still partially visible but most often is an indication that the user is leaving the activity and will soon may enter in stopped state.

onStop()  and onDestroy() –  Activity is no longer visible to user.

The life cycle of an activity with its most important methods is displayed in the following diagram.

activity6

An activity has some more methods in addition to above but all of these methods are not guaranteed to be called. For example the onDestroy() method is not guaranteed to be called, hence you mostly we don’t use or mention it.

Typically we use the onPause() method to stop framework listeners and UI updates and onStop() method to save the application data. These methods are guaranteed to be called before the activity is terminated.

The onResume() is used to register the listeners again and to trigger UI updates based on the saved data.

Activity instance state

Instance state of an activity is required to restore the activity to the state in which the user left it. This is non-persistent application data that needs to be passed between activities restarts during a configuration change to restore user selections. The application is responsible for restoring its instance state.

For example when user scrolls through a ListView which has a number of items, repeatedly the activity is recreated each time user scrolls. In that case loosing the item position in the list is annoying for the user; hence the position should be restored. The onSaveInstanceState() can be used to store this instance state as a Bundle.

A Bundle can contain primitive data types, arrays, String and objects which are of the Parcelable or Serialisable type. The persisted Bundle data is passed at restart of the activity to the onCreate() method and onRestoreInstanceState() as parameter.

You should always prefer to use the onRestoreInstanceState() method for restoring the instance state. This approach separates the initial setup from restoring the state. If the user interacts with an activity and presses the Back button or if the finish() method of an activity is called, the activity is removed from the current activity stack and recycled. In this case there is no instance state to save and the onSaveInstanceState() method is not called.

If the user interacts with an activity and presses the Home button, the activity instance state must be saved. This is the case when onSaveInstanceState() method is called. If the user restarts the application it will resume or restart the last running activity. If it restarts the activity it provides the bundle with the save data to the onRestoreInstanceState() and onCreate() methods.

Fixing the orientation for an activity

If user wants that his app or activity should only be used in a specific screen orientation then this can be done by some configuration settings into the AndroidManifest.xml file. Such an example configuration is listed below.

 

 

 

Above lines in your manifest will make sure that app or activity runs in portrait mode only.

Create project

This example will help you to observe how the life cycle methods of the Android system work into your Android application. Create a new project called com.example.lifecycleactivity. Create the following class which will show a message whenever a life cycle method is called.

 

 

 

Write following into your layout xml

 

 

 

Run to see the output below:

activity7

activity8

Declaring the activity in the manifest 

You must declare your activity in the manifest file in order for it to be accessible to the system. To declare your activity, open your manifest file and add an <activity> element as a child of the <application> element. For example:

 

 

 

There are several other attributes that you can include in this element, to define properties such as the label for the activity, an icon for the activity, or a theme to style the activity’s UI. The android: name attribute is the only required attribute—it specifies the class name of the activity. Once you publish your application, you should not change this name, because if you do, you might break some functionality, such as application. See the <activity> element reference for more information about declaring your activity in the manifest.

You can shut down an activity by calling its finish() method. You can also shut down a separate activity that you previously started by calling finishActivity(). In most cases, you should not explicitly finish an activity using these methods. As discussed in the following section about the activity lifecycle, the Android system manages the life of an activity for you, so you do not need to finish your own activities. Calling these methods could adversely affect the expected user experience and should only be used when you absolutely do not want the user to return to this instance of the activity. 

Implementing a user interface

The user interface for an activity is provided by a hierarchy of views—objects derived from the View class. Each view controls a particular rectangular space within the activity’s window and can respond to user interaction. For example, a view might be a button that initiates an action when the user touches it.

Android provides a number of ready-made views that you can use to design and organize your layout. “Widgets” are views that provide visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image. “Layouts” are views derived from ViewGroup that provide a unique layout model for its child views, such as a linear layout, a grid layout, or relative layout. You can also subclass the View and ViewGroup classes (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.

The most common way to define a layout using views is with an XML layout file saved in your application resources. This way, you can maintain the design of your user interface separately from the source code that defines the activity’s behavior. You can set the layout as the UI for your activity with setContentView(),  passing the resource ID for the layout. However, you can also create new Views in your activity code and build a view hierarchy by inserting new Views into a ViewGroup, then use that layout by passing the root ViewGroup to setContentView().

Coordinating activities

When one activity starts another, they both experience life cycle transitions. The first activity pauses and stops (though, it won’t stop if it’s still visible in the background), while the other activity is created. In case these activities share data saved to disc or elsewhere, it’s important to understand that the first activity is not completely stopped before the second one is created. Rather, the process of starting the second one overlaps with the process of stopping the first one.

The order of life cycle callbacks is well defined, particularly when the two activities are in the same process and one is starting the other. Here’s the order of operations that occur when Activity A starts Acivity B:

  1. Activity A’s onPause() method executes.
  2. Activity B’s onCreate(), onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)
  3. Then, if Activity A is no longer visible on screen, its onStop() method executes.

This predictable sequence of lifecycle callbacks allows you to manage the transition of information from one activity to another. For example, if you must write to a database when the first activity stops so that the following activity can read it, then you should write to the database during onPause() instead of during onStop(). Let’s have a look on the code sample below which show how to start another activity within same application:

Create a new android project and write below into mainActivity.java:

 

 

 

Now write below in main layout file:

 

 

 

Create and write below in Second activity.java:

 

 

 

Create and write below into second layout xml:

 

 

 

Add your new activity into manifest

 

 

 

Run for the output below:

activity10

activity9

Fragments

Introduced in API level 11A Fragment represents a behavior or a part of user interface in an Activity. You can combine various fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. Fragments can be imagined as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running. It is a kind of a “sub activity” that you can reuse in different activities.

When you add a fragment as a part of your activity layout, it lives in aViewGroup inside the activity’s view hierarchy and the fragment defines its own view layout. You can insert a fragment into your activity layout by declaring the fragment in the activity’s layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup. However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.

Here I will show you how to build your application to use fragments, including how fragments can maintain their state when added to the activity’s back stack, share events with the activity and other fragments in the activity and more.

The goal behind introducing fragments is to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet’s screen is much larger than that of a handset, there’s more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy. By dividing the layout of an activity into fragments, you will be able to modify the activity’s appearance at run-time and preserve those changes in a back stack that’s managed by the activity.

For example, a news application can use one fragment to show a list of articles on the left and another fragment to display an article on the right—both fragments appear in one activity, side by side, and each fragment has its own set of life cycle callback methods and handle their own user input events. Thus, instead of using one activity to select an article and another activity to read the article, the user can select an article and read it all within the same activity, as illustrated in the tablet layout in the image below:

Each fragment should be designed as a modular and reusable activity component. This is especially important because a modular fragment allows you to change your fragment combinations for different screen sizes. When designing your application to support both tablets and handsets, you can reuse your fragments in different layout configurations to optimize the user experience based on the available screen space. For example, on a handset, it might be necessary to separate fragments to provide a single-pane UI when more than one cannot fit within the same activity.

activity11

This is an example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for a handset design.

The overview screen (also referred to as the recent screen, recent task list, or recent apps) is a system-level UI that lists recently accessed activities and tasks and is a very good and common example of use of fragments. The user can navigate through the list and select a task to resume, or the user can remove a task from the list by swiping it away. With the Android 5.0 release (API level 21), multiple instances of the same activity containing different documents may appear as tasks in the overview screen. For example, Google Drive may have a task for each of several Google documents. Each document appears as a task in the overview screen.

Normally you should allow the system to define how your tasks and activities are represented in the overview screen, and you don’t need to modify this behavior. However, your app can determine how and and when activities appear in the overview screen. The ActivityManager.AppTask class lets you manage tasks, and the activity flags of the Intent class let you specify when an activity is added or removed from the overview screen. Also, the <activity> attributes let you set the behavior in the manifest.

Loaders

Loaders make it easy to asynchronously load data in an activity or fragment. They are introduced in android 3.0. Apart from the definition loaders have following characteristics:

  1. They are available to every Activity and Fragment.
  2. They provide asynchronous loading of data.
  3. They monitor the source of their data and deliver new results when the content changes.
  4. They automatically reconnect to the last loader’s cursor when being recreated after a configuration change. Thus, they don’t need to re-query their data.

This here ends this tutorial where we have seen theory on activity, how it works in android, fragments and loaders a part of activity. Hope you enjoyed reading this. J Continue reading my posts to get more on android components.

This was all about activity. Thanks.

Leave a Comment: