Android Tutorial (2) – Applications key concepts, activities and resources

In order to understand the Android application architecture you need some basic knowledge regarding Android applications key concepts. Understanding these elements will allow you to control:

  • application components
  • application lifecycle
  • application resources

In this post are described all these key concepts  in order to highlight their role, utility and importance. Other posts will describe in more detail how are used in order to develop an Android mobile application.

The main characteristics of an Android application (more detailed information on developer.android.com) are:

  • it is a Java application executed by a Dalvik Virtual Machine; the Dalvik VM runs .dex files, obtained from Java .class files;
  • it is distributed in an Android Package, which is a .apk file;
  • it is executed by the Android Operating System (a multi-user Linux) in a sandbox; each application has a unique user ID and its resources can be accessed only by that user; each application runs in its own Linux process and its own Virtual Machine instance; despite this, two different applications can be assigned same user ID in order to share their resources;
  • critical operations (access to Internet, read or write contacts, monitor SMS, access GPS module) can be restricted or can require user permission, using the application manifest file, AndroidManifest.xml; more detailed info on the Android application security are available at http://developer.android.com/guide/topics/security/security.html;
  • an Android application is represented by one or more activities (an activity can be associated with a user screen or window, but is more than that) and Linux process; an activity lifecycle is not related to the application process lifecycle; the activity can run even if its process doesn’t exists any more (this is different than C,C++ or classic Java applications where an application has a process);
  • an application can start a component (activity) from another application; the component is executed by its parent application process;
  • an Android application does NOT have a single entry point, like the main() method in Java, C or C++ applications;

Other topics that are part of this Android tutorial are accessible through Android Tutorial – Overview and contents.

Components of Android applications

The most important components of the Android application are:

Activity

  • represents a user interface screen, window or form;
  • an Android application can have one or more activities; an agenda application can have an activity to manage contacts, an activity to manage meetings and one to edit an agenda entry;
  • each Activity has its own lifecycle independent from the application process lifecycle;
  • each Activity has its own state and it is possible to save it and restore it;
  • activities can be started by different applications (if it is allowed);
  • has a complex lifecycle because applications can have multiple activities and only one is in the foreground; using the Activity Manager, the Android System manages a stack of activities which are in different states (starting, running, paused, stopped, destroyed);
  • in the Android SDK is implemented using a subclass of Activity class which extends the Context class;

Intent

  • represents an entity used to describe an operation to be executed; is a message transmitted to another component in order to announce an operation;
  • somehow similar to the event-handler concept from .NET or Java;
  • an asynchronous message used to activate activities, services and broadcast receivers;
  • implemented by the Intent class;

Service

  • a task that runs in the background without the user direct interaction;
  • implemented by a subclass of Service;

Content provider

  • a custom API used to manage application private data;
  • an data management alternative to the file system, the SQLite database or any other persistent storage location;
  • implemented as a subclass of ContentProvider;
  • a solution to share and control (with permissions) data transfer between applications (i.e. Android system provides a content provider for the user’s contact information);

Broadcast receiver

  • a component that responds to system-wide broadcast announcements;
  • somehow similar to the global (or system event) handler concept;
  • implemented as a subclass of BroadcastReceiver

Activity LifeCycle

The Android application Activity is one of the most important component (with services and broadcast receivers) of Android applications because it is related to the user interface. An activity is used to manage a user screen and is equivalent to the window or form form desktop applications.

Understanding and knowing how to control the Activity allows you to:

  • use the Activity lifecycle to create, view, use and stop activities;
  • save user data before the Activity is stopped and restore it when it is brought back to the foreground;
  • create applications with multiple views or activities;

The Activity lifecycle describes the state in which an Activity can be at one moment:

Running – the Activity has been created (onCreate()) and started (onStart()) and it is displayed on the device screen; if the Activity was used before and the application has saved its state (onSaveInstanceState()), it is resumed from that point (onRestoreInstanceState() and onResume()); in this state the user interacts with the Activity through the device input interface (keyboard, touchscreen, display);

Paused – the Activity looses the foreground position (onPause()) because another Activity is executed, like a dialog box or alert; also, if the device enters sleep mode, the Activity is paused; the activity may resume its execution (onResume()) and placed back to the foreground;

Stopped – the Activity is not more in use and because it is stopped (onStop()) is not visible; in order to be reactivated (the Activity already exists), the Activity must be restarted (onRestart() and onStart()) and resumed (onResume());

Destroyed – The Activity is destroyed (onDestroy()) and its memory is released because it will not be needed or the systems needs more memory; because memory management is an important issue for the Linux OS of the mobile device, the process that hosts the paused, stopped or destroyed Activity can be killed to release memory for new activities; only processes that hosts running activities are protected;

Android Activity Lifecycle Diagram
Android Activity Lifecycle Diagram

As you can see in the previous image the Activity has multiple states with clear transitions between them. Despite things may look complicated, in reality they are much more simpler if you keep in mind the next facts:

  • only one Activity can be in the foreground;
  • the system manages the states and the transitions, NOT the programmer (not directly, because when you start a new Activity you implicitly change the state of the current one)
  • IMPORTANT the system notifies you when the Activity is going to change its state providing handlers (the onXXX() methods) for the transitions events; as a programmer, you can add your own code by overriding these methods:

onCreate(Bundle) – called when the Activity is created; using the method argument you can restore the Activity state that has been saved from a previous session; once the Activity has been created is going to be started (onStart());

onStart() – called when the Activity is going to be displayed; from this point the Activity can come to the foreground (onResume()) or stay hidden (onStop());

onRestoreInstanceState(Bundle) – called when the Activity is initialized with data from a previous saved state; by default, the system restores the state of the user interface;

onResume() – called when the Activity is visible and the user can interact with it; from this state, the Activity can go in the background becoming paused (onPause());

onRestart() – called when the Activity is going back to the foreground from a stopped state; after that, the Activity is started (onStart()) once again;

onPause() – called when the system is bringing into the foreground another Activity; the current Activity is set into the background and later it may be stopped (onStop()) or resumed and displayed (onResume()); this is a good moment to save application data to a persistent storage (files, database)

onSaveInstanceState(Bundle) – called to save the Activity state; by default, the system saves the state of the user interface;

onStop() – called when the Activity is not longer used and not visible as another Activity is interacting with the user; from this point, the Activity can be restarted (onRestart()) or destroyed (onDestroy());

onDestroy() – called when the Activity is deleted and its memory released; this can happen if the system requires more memory or if the programmer terminates it by calling the Activity finish() method;

Because the state transitions are regulated by different calls to onXXX() methods, the Activity lifecycle can be described by their possible calling sequence:

Events Handlers for Android Application Activity
Events Handlers for Android Application Activity

In order to override the methods you must pay attention to their name and signature. It’s safer to use the @Override annotation and request a validation from the compiler (if the defined method does not override a method from the base class then you will get a compiler error).

For onCreate() or onPause() the solution is:

public class SomeActivity extends Activity {
	// The activity is being created.
    @Override
    public void onCreate(Bundle savedInstanceState) {
	// DO NOT forget to call the base method
        super.onCreate(savedInstanceState);
    }

	// Another activity is put in the foreground.
    @Override
    protected void onPause() {
	// DO NOT forget to call the base method
        super.onPause();
    }
}
Important !
When you override one of the onXXX() methods, you must call (must be the first statement in the method) the base class (Activity) method because the scope of this approach is to add your own code to the Activity events and NOT to reinvent them.
Important !
As you can see in the previous two figures, the Activity can have states, like Stopped and Destroyed, in which the device OS can kill the process that hosts the Activity. The OS will release the Activity memory without calling the onStop() and onDestroy() methods. In conclusion, the onPause() event is the recommended moment for saving Activity state before it will be destroyed.

Android Application Resources

Applications use text strings, bitmaps, video and audio files to enhance the user experience. All these represent resources. Despite they are controlled from the source code they are external resources and the recommendation is to externalize (not storing them in the application code) them in order to support:

  • internalization by providing different languages and format user interface
  • application portability on different devices

Resources are stored in the res directory inside the Android project. In order to manage different types of resources, the project res directory contains specific subfolders:

DirectoryResource
res/animator/XML files that define property animations.
res/anim/XML files for tween animations.
res/color/XML files that define colors and color state list resource.
res/drawable/Bitmap files (.png, .jpg, .gif) or XML files that define drawable resource subtypes.
res/layout/XML files that define a user interface layout.
res/menu/XML files that define application menus.
res/raw/arbitrary files in their raw format (binary or text files)
res/values/XML files that contain simple values, such as strings, integers, and colors. It is recommended to use filename conventions for particular types of resources: arrays.xml (typed arrays), colors.xml (color values), dimens.xml (dimension values), strings.xml (string values), styles.xml (styles).
res/xml/XML files that can be read by calling Resources.getXML()

All the resources from the res subdirectories are packed by the compiler. In order to facilitate the access and control of resources from the application cod, the compiler generates a class, called R, that contains static identifiers used to reference each resource.

Important !
Because resource files are compiled, DO NOT save resource files directly inside the res/ folder because it will cause a compiler error.

For example, it is recommended to define and store constant String values inside the res/values/strings.xml and NOT to write them directly into the code. Being defined outside the code it means that you can modify them without affecting the Java source code. The strings.xml file may look like this

<!--?xml version="1.0" encoding="utf-8"?-->

    Hello World, Activity!
    Android

As said before, for each resource the compiler generates a static unique identifier in the R class. The static indentifier has the same name as the strings.xml element.

package itcsolutions.eu;

public final class R {
    //...

    public static final class string {
        //unique ID for app_name string in strings.xml
        public static final int app_name=0x7f040001;
        //unique ID for hello string in strings.xml
        public static final int hello=0x7f040000;
    }
}

So, if I want to get the hello element value and copy it into a String variable, I will use the static reference:

        String stringHello = this.getString(R.string.hello); 

Other topics that are part of this Android tutorial are accessible through Android Tutorial – Overview and contents.

Like it? Then share this post or check the external adds. Sharing is the best way to appreciate the author.