≡ Menu

How to Write an Android App with Activity Lifecycle Function Examples

Building a basic Android App is relatively easy once you understand the fundamentals.

This tutorial will give you a brief introduction on Android Activity Lifecycle, the files and functions that are involved in building an Android App.

This should get you started in the right direction and help you to build your own Android app.

I. Android App Files

First, make sure you download and install the ADT Android Developer Tool on you system.

When you create a project (BlankActivity) in ADT, the following 5 files will be created by ADT Blank Activity template (with “Create customer launcher icon” and “Create activity” selected).

1. src/com/projectdomain/appname/

An App must have at least one activity as configured in AndroidManifest.xml file. The main activity exists in MainActivity.java. The directory hierarchy follows the naming convention of java packages. Project domain can be any string, but com.example is reserved by Google, and it doesn’t allow any public App in Google Play under this name.

Android is designed by keeping multi-language and multi-device support in mind from the very beginning. So, most of the resources are mainly described in xml files.

2. res/layout

First of all, we must indicate how the components are laid out on the screen. Since the app may run under various screen resolutions, more than one layout can be defined. By default, activity_main.xml file is used by MainActivity.java in onCreate() function.

setContentView(R.layout.activity_main);

If you want to optimize the layout for different screen orientation or size, you should add a new layout directory with suffix -land and -large. Otherwise, OS will auto-scale and choose the layout.

3. res/values/

Besides layout, the next important thing for GUI is the content displayed to the user. As mention above, in order to support multiple languages, strings used by the App are all defined in an xml file. By default, there is a strings.xml which is also used by MainActivity.java

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Test&t;/string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
</resources>

If you want to support other languages, add new values directory with suffix -country code, which can be found in ISO 639-1. Android OS will auto-select strings for your locale if available.

Besides strings, you can also use xml files for dimension and style definitions. dimens.xml for dimensions and styles.xml for styles.

The following code can be found in layout/activity_main.xml file for configuration of padding information.

    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"

The following code can be found in AndroidManifest.xml for theme configuration.

    android:theme="@style/AppTheme"

4. res/drawable/

This directory stores drawable resources (such as bitmaps and icons). By default, ic_launcher.png file used as icon for the app.

As for different screen sizes, there are several drawable directories, distinguished by the suffix -xxhdpi, -xhdpi, -hdpi, -mdpi, and -ldpi. Take mdpi as baseline, xxhdpi has density of 3.0, xhdpi 2.0, hdpi 1.5, and ldpi 0.75.

When referring the resource in code, you don’t need to specify the density, as OS will choose the appropriate one automatically. ldpi can also be left to OS, as 2:1 downscale from hdpi is relatively easy.

5. AndroidManifest.xml

This file defines manifest information for the application which includes permission, broadcast receivers, sdk api level, etc. all. When adding code that needs extra permission, higher api level, or to receive broadcast message, corresponding element of this file should also need to be updated.

For ADT, when you are using function that need higher API level, there will be a tip showed near the function call.

II. Android App Activity Lifecycle

An Android Activity has many states in its lifecycle. The following is the Android activity lifecycle sequence.

OS -> Created -> Started -> Resumed -> Paused -> Stopped -> Destroyed

When entering a state, the responding callback function (onStateName) will be called.

Created and Started are transient states which means that App will go to Resumed state without stop. App will be in Paused state when it’s partially visible, such as covered by another full screen semi-transparent activity. If the App occupies the screen again, it will go back to Resumed state. When the App totally goes into the background (not visible to user), it will go into Stopped state.

So we can add the first loop denoted by “()” into the lifecycle as shown below.

OS -> Created -> Started -> (Resumed -> Paused) -> Stopped -> Destroyed

For better response, Android will not be so tight on destroying the App instance, so when loosing focus (when user is in other activity/app), the App will go into Paused or Stopped state. In another words, activity goes to Stopped state, when its focus is interrupted by other activity. This is not a big issue as the onboard memory of mobile devices are getting bigger and bigger. When user is back on the activity again, it goes into Started state and then to Resumed state. Different from the first launch, there is no Created state this time, but an extra OnRestart will be called.

So we can add a second loop denoted by “[]” into the lifecycle as shown below.

OS -> Created -> [Started -> (Resumed -> Paused) -> Stopped] -> Destroyed

The second loop takes place when user re-entered the app by using Launch icon or Recent Apps, or foreground activity ends and makes the stopped activity foreground.

In Destroyed state, the instance is destroyed completely. Usually, as long as there is enough memory, the instance will be kept in memory in Stopped state. When OS decides to grab more resources, the Stopped instance maybe killed. But Android cannot guarantee that the onDestroy will be called properly before destroying the instance.

So there is a third loop denoted by “{}” in OS’s view, but it is composed of two different lifecycle for the activity as shown below.

OS -> {Created -> [Started -> (Resumed -> Paused) -> Stoped] -> Destroyed
     -> Created -> [Started -> (Resumed -> Paused) -> Stoped] -> Destroyed}

III. Main Callback Functions

onStart will let LoaderManager to start working, but this stage is not so important to user application. For user application, onPause and onStop will do most of the cleanup, so most activity does not need to implement the onDestory method.

The following are the 6 callbacks that are frequently used in an Android App.

1. onCreate(Bundle)

The component and other resources will be created in this function. This is more or less the same for all programs. In this function, we should make everything ready, and wait to interact (Resumed state) with the user. The Created state will not stay. So, it’s not wise to call any working function here. Since GUI is not fully brought up at this stage, most GUI related function will not work in this state.

By default, only setContentView is called.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

2. onResum

Interaction (such as playing a background music) should start from onResum function. As Resumed state will be entered multiple times, if object declaration is done in here, do not forget to check the validity of object first.

3. onPause

Pause state indicates that user is not in this App, but user can still see part of this App. So, in this function, stop the interaction with user, and release resources (such as audio, video) for other App’s to access.

4. onStop

The function will be called when the user is about to completely leave the App. Resource release and state saving operation (such as saving draft to a file) could be done in this function.

Please keep in mind that when an activity is self-finished or destroyed, such as Back is pressed or finish() is called, nothing will be left. But, OS may kill/destroy the instance. So, besides saving the working state, other data used in UI should also be saved here, such as text in a EditView, progress of video playback, etc.

5. onSaveInstanceState(Bundle savedInstanceState)

For View object, OS will help to save it for us, but for Application specified information, it is developer’s job to save those. onSaveInstanceState and onRestoreInstanceState are used for this purpose

Extra information should be saved here, which is called before entering the Destroyed state. We can put all necessary variables to the Bundle, so we don’t forgot what we are doing.

6. onRestoreInstanceState(Bundle outState)

We can retrieve the stored variables from Bundle either in onRestoreInstanceState or onCreate.

Note that, when user rotates the screen, destroy and create state sequence will be triggered. If rotation is enabled, these two function (5, and 6) must be implemented, so that user will continue do what he is doing after the rotation. Callback function 2-6 are not implemented by default, it can be added by ADT -> Source -> Override/Implement Methods.

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

{ 3 comments… add one }

  • Navis Michael Bearly. J November 19, 2013, 1:10 am

    Is it common to all android versions of development.

  • Jalal Hajigholamali November 19, 2013, 1:22 am

    Hi,

    Good article, Thanks a lot…

  • Guruprasad December 3, 2013, 12:53 pm

    Sir,
    The article is really good.
    I request you to provide more articles on Android app from you.

    Regards,
    Guru.

Leave a Comment