Phone Icon Android Mobile Operating System

Android™ is an open-source operating system which powers millions of mobile devices across the world. See these links for details about the history of mobile operating systems, Android history, and the distribution of Android usage by version. Also see the Android Developers website.

Software Stack | Terminology | XML Files | Layouts | Activities | Fragments | Intents | Intent Extras | Activity State | Shared Preferences | Spinners | List Views | Menus | WebViews | Custom Views
Android Software Stack Linux Kernel, WebKit, SQLite, OpenGL

Each Android application runs in its own instance of Dalvik Virtual Machine (DVM). Similar to a Java Virtual Machine (JVM), the DVM has been optimized for hardware that has limited resources (memory, CPU power). Android applications are typically written in Java and interface with the Android API, which was mostly written in Java.

Android is built on top of a Linux V2.6+ kernel. This is a basic hardware abstraction layer. The software at the kernel level includes:

Display Driver
Keypad Driver
Camera Driver
WiFi Driver
Flash Memory Driver
Audio Drivers
Binder (iPC) Driver
Power Management

The next layer in the Android stack is Library stack. These are mostly coded in C and C++. They include:

Surface Manager (Screen Manager)
OpenGL (3D graphics)
SGL (2D graphics)
Media Framework (Wide variety of media formats)
FreeType (fonts)
SSL (Secured Sockets)
SQLite (Database)
WebKit (Web Rendering Engine)
libc (standard C libraries)

The third layer is the Application Framework. These modules are mostly coded in Java. These modules make up the API which are used by developers when building applications:

Activity Manger
Window Manager
Content Providers
View System
Package Manager
Telephony Manager
Resource Manager
Location Manager
Notification Manager

The top layer contain applications, such as:

Phone
Browser
Developed Apps


Android Terminology How to Speak to an Android

Some of the terms used in Android development are:

Context
The Context class provides access to the Android system for such underlying services as resolving resources, accessing databases, and obtaining environment information. Formally defined: The Context class is an interface to global information about an application environment.
Activity
Typically, the Activity class provides a screen with which users can interact in order to do something, such as dial the phone, take a photo, send an email, or view a map. Each activity is given a window in which to draw its user interface. Formally defined: An activity is a single, focused thing that the user can do. Activities are often presented to the user as full-screen windows.
Fragment
A fragment represents a particular operation or interface running within a larger activity. Fragments enable more modular activity design, making it easier to adapt an application to different screen orientations and multiple screen sizes. Formally defined: A Fragment represents a behavior or a portion of user interface in an Activity.
Intent
An intent can be considered as an intention to do an action. Intent interfacing provides a way to transition from one activity to another. An Intent object is a bundle of information. It contains information of interest to the component that receives the intent, plus information of interest to the Android system. Formally defined: An intent is an abstract description of an operation to be performed.
 
A service is a background process that has no user interface. Formally defined: A Service is an application component that can perform long-running operations in the background and does not provide a user interface.
View
An object that draws to a rectangular area on the screen and handles click, keystroke, and other interaction events. A View is a base class for most layout components of an Activity or Dialog screen (text boxes, windows, and so on). It receives calls from its parent object (see viewgroup, below)to draw itself, and informs its parent object about where and how big it would like to be (which may or may not be respected by the parent).
Viewgroup
A container object that groups a set of child Views. The viewgroup is responsible for deciding where child views are positioned and how large they can be, as well as for calling each to draw itself when appropriate. Some viewgroups are invisible and are for layout only, while others have an intrinsic UI (for instance, a scrolling list box). Viewgroups are all in the widget package, but extend ViewGroup.
Widget
One of a set of fully implemented View subclasses that render form elements and other UI components, such as a text box or popup menu. Because a widget is fully implemented, it handles measuring and drawing itself and responding to screen events. Widgets are all in the android.widget package.
Intent Filter
A filter object that an application declares in its manifest file, to tell the system what types of Intents each of its components is willing to accept and with what criteria. Through an intent filter, an application can express interest in specific data types, Intent actions, URI formats, and so on. When resolving an Intent, the system evaluates all of the available intent filters in all applications and passes the Intent to the application/activity that best matches the Intent and criteria.
Broadcast Receiver
An application class that listens for Intents that are broadcast, rather than being sent to a single target application/activity. The system delivers a broadcast Intent to all interested broadcast receivers, which handle the Intent sequentially.
Content Provider
A data-abstraction layer that you can use to safely expose your application's data to other applications. A content provider is built on the ContentProvider class, which handles content query strings of a specific format to return data in a specific format.
Dalvik
The Android platform's virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included "dx" tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.

Android XML Files Android Application: Program Code and Resources
Note: See Android Development - XML for example code of XML files.

Android uses a combination of program code and resource data (stored in XML files) to define applications. Application behaviors, layout, and resources can be declared in XML files. A file named AndroidManifest.xml must be included in the root directory of every Android project. The file contains essential information about the project to the Android operating system. Android uses the information in this file to

User Interface - Layout Files

Android can use either program code or XML resource files for declaring and managing the user interface. In Android, a View is an object that draws on the screen and handles user interactions. A View is a base class for most layout components of an Activity or Dialog screen. Typically the layout components are declared with XML files and program code is used to interact with the components. This approach separates the application's presentation from the code that controls its behavior. This separation allows multiple GUIs to be developed for different device screens with only one code base required for an application. However there are occasions where the layout components are created by the program code.

The Eclipse ADT plugin has a Graphical Layout tool for creating the layout components as XML files. In the project's res/layout folder is an activity_main.xml file. In the Graphical Layout tool you can drag and drop a GUI component, such as a button, on to the screen form. You can then see the XML code has been generated in the activity_main.xml file for the button. In addition, Eclipse's Hierarchy Viewer tool allows you to change the components properties and see the resulting changes in the Graphical Layout emulator.

Each GUI layout XML file must contain exactly one root element, which must be a View or a ViewGroup. Additional elements can be defined inside the root element to build a view hierarchy. When compiled, each XML layout file defines a View resource in the auto-genterated R.java file. The view resource should be specified in the callback function of the setContentView method in the onCreate object.

String Resources

It is good programming practice to specify the application's data content in XML resource files. String values are stored in the res/layout folder in the strings.xml file. Note when you use the Graphical Layout tool to create a GUI component, the content value may be hard coded. This can be converted to a string resource thru these menu options: (Refactor, Android, Extract Android String). Also, the data contents can be edited directly in the XML files (sometimes more reliable) or through the use of the Resources editor. For example you can edit the XML files to add bold <b> and italics<i>.

Attribute Resources

Every object has its own variety of XML attributes. An attribute that is common among the objects is the ID attribute. Below is an ID attribute for a button defined in the activity_main.xml file.

android:id="@+id/button1"

The @ symbol signals the XML parser that the remainder of the string should be identified as an XML resource. The + symbol indicates it is a new ID resource that has not been declared before. When compiled, the attribute in the XML file will be translated into a number, as shown in this line from the R.java file below. When using a Relative Layout, IDs are important because the location of the GUI components are specified in relationship to other GUI components, which are referenced by IDs.

public static final int button1=0x7f090000;


Screen Layouts Frame, Linear, Table, Relative
Note: See Android Development - Screen Layouts for example code of XML layouts.

Android has layout classes that help position the GUI components on a screen. Layouts do not display anything, but they contain and arrange the GUI components in desired positions. Layouts can be created in either XML or program code. Four common layout classes are:

1. FrameLayout
FrameLayout treats the entire screen as one space that can be filled with a single object. All the components are drawn at the upper-left corner of the screen. Subsequent components will overlay earlier components. Below two buttons were put into a FrameLayout; only the second button shows in the running application.

Frame Layout
 

2. LinearLayout
LinearLayout aligns all the components in either a horizontal or vertical direction. LinearLayout recognize margins, gravity, and weights.

Vertical LinearLayout is like a stack of pancakes.
In vertical LinearLayout the components can be stretched vertically by adding weight and positioned horizontally by adding gravity.

img4

LinearLayout - Vertical


Weight(1,0,0)
Gravity(u,right,1)


Horizontal LinearLayout is like slicing bread.

In Horizontal LinearLayout the components can be stretched horizontally by adding weight and positioned vertically by adding gravity.

img3

LinearLayout - Horizontal

Weight(1,0,0)
Gravity(u,bottom,u)


3. TableLayout
TableLayout positions the components into rows and columns. Each table cell can contain a GUI component or another layout class.

img5

TableLayout

Weight(1,1,0,0)
Gravity(u,u,u,u)


4. RelativeLayout
RelativeLayout positions components in relationship to the parent view or other components (specified by ID). Positioning attributes include: alignParentTop, alignParentLeft, alignLeft, below, ...

img6

RelativeLayout



Android Activities Creation, Life Cycles, Intents, Saving State
Note: See Android Development - Activities for steps to create an activity and example code.

An Android Activity is a process with a screen for user interaction. Unlike traditional applications, each activity is independent of the other activities. Activities can not directly call the methods of another activity. Instead an activity will send an Intent to the Android system. For Implicit Intents, the startActivity() method is invoked and the registered activity for that intent is started. IntentFilters specify (in AndroidManifest.xml) the type of Intents for which an activity can respond. For Explicit Intents the exact components which should be called by the Android system are defined. Data can not be passed between activities in the traditional manner (like through parameters), but require special mechanisms , such as Intent Extras, for sharing "bundles" of data.

Applications can contain multiple activities, but one activity is designated as the main activity which launches the application. When a new activity starts, the previous activity is pushed onto the "back stack". When an activity is preempted by a new activity, the previous activity is notified of the reason and is given an opportunity to take appropriate action. Such as preserve its state, release resources, etc.

When a new activity is created it MUST be defined in the manifest in order for it to me accessible by Android. An activity can also define Intent Filters which declares how other applications can use it. Each activity is a subclass of the Activity class and must implement an onCreate() method. An activity can be started with either the startActivity() or startActivityForResult() methods. An activity is ended by calling its finish() method.

An activity basically has three states:

  1. Resumed - Activity in foreground and has focus.
  2. Paused - Still visible, but another activity is in foreground and has focus.
  3. Stopped - Still in memory, but no longer visible. Another activity is in foreground and has focus. The stopped activity can be killed by Android if it is in need of memory.

Various callback methods are used as an activity transitions among the different states, such as: onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy().

  1. The entire lifetime happens between the first call to onCreate() and the final call of onDestroy().
  2. The visible lifetime happens between a call to onStart() until a corresponding call to onStop().
  3. The foreground lifetime happens between a call to onResume() until a corresponding call to onPause().
  4. onPause() is typically used to commit changes to data and otherwise prepare to stop user interaction.
  5. All activities must implement onCreate() which will perform the initial setup.

The relationships are visible in the following Activity Lifecycle Diagram:

Activity Lifecycle


Diagram: Activity Lifecycle



The entire lifecycle of an activity is defined by the following methods. Any of these methods can be overridden to do the desired work when an activity changes state:

public class Activity extends ApplicationContext {

protected void onCreate(Bundle savedInstanceState);

protected void onStart();

protected void onRestart();

protected void onResume();

protected void onPause();

protected void onStop();

protected void onDestroy();
}
Fragments Activity Fragments

A fragment is a modular section of an activity. You can combine multiple fragments in a single activity to build a multi-pane UI. You can resuse a fragment in multiple activities. A fragment has its own lifecycle and its own input events. Fragments define their own view layouts. You can insert a fragment into an activity layout. Fragments were introduced in API 11 to support more flexible UI designs on larger screens (tablets). Fragments are created as a subclass of the Fragment class and has code that looks much like an activity. Fragment Manager is used to manage fragments within an activity. More information about fragments is available at the Android Developers section on fragments.


Intents Implicit and Explicit
Note: See Android Development - Intents for a coding example of how to code an intent.

Intents allow the application to move between different activities and to start services. Android activities do not directly call each other. Instead they send an Intent to the Android operating system which determines which process should be started. There are two types of intents:

  1. Implicit Intent - does not specify a component to be run. Instead they provide enough information for the system to determine which of the available components is the best to run for the intent.

  2. Explicit Intent - does specify a component to be run.

If the activity has data to be shared, instead of using a traditional method like parameter passing, the data must be put in a bundle to be included with the Intent as an Intent Extra.

Intent Extras Sharing Data between Activities

Instead of activities directly calling each other, they send an Intent to the Android system. If the activity has data to be shared, instead of using a traditional method like parameter passing, they store the data in a bundle that is included with the Intent. Intent Extras is the name of this mechanism for including data along with an Intent. Intent Extras consist of data bundles accessed by the putExtra() and getExtra() methods. The data is defined in key-value pairs. Below is an example of how to code intent extras to share data between activities:

  1. Create an explicit intent for the Dosage activity with extra data put into a bundle.
    
    
    Intent launchDosageActivity = new Intent(this, dosageActivity.class); launchDosageActivity.putExtra("dosageTime", time); launchDosageActivity.putExtra("dosageName", name); launchDosageActivity.putExtra("dosageStrength", strength); startActivity(launchDosageActivity);
  2. Get the Extra data from the bundle and assign to screen fields.

    
       public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.dosage);
    
          // Get Extra Data from Bundle
          Bundle extras = getIntent().getExtras();
          if (extras != null) {
             dosageTime = extras.getString("dosageTime");
             TextView dosageTimeTV = (TextView) findViewById(R.id.dosageTimeTV);
             dosageTimeTV.setText(dosageTime);
    
             dosageName = extras.getString("dosageName");
             TextView dosageNameTV = (TextView) findViewById(R.id.dosageNameTV);
             dosageNameTV.setText(dosageName);
    
             dosageStrength = extras.getString("dosageStrength");
             TextView dosageStrengthTV = (TextView) findViewById(R.id.dosageStrengthTV);
             dosageStrengthTV.setText(dosageStrength);
          }
    

Saving and Restoring Activity State onSaveInstanceState, onRestoreInstanceState
Note: See Android Development - State for a coding example of saving and restoring activity state.

Android will destroy activities when certain device configurations change, such a screen orientation. When the screen orientation changes, Android destroys the running activity and recreates it. Android calls the onSaveInstanceState() before it destroys an activity. The method stores the state information in a data bundle to be used if the user should navigate back to the activity. Android is then able to recreate the activity and it would not be evident to the user that the activity was ever destroyed. Android automatically saves and restores the state data that is inherently part of a view. However, it is sometimes necessary to override the onSaveInstanceState() and onRestoreInstanceState() to save additional state data.


Shared PreferencesData Persistence
Note: See Android Development - Shared Preferences for a coding example of how to code shared preferences.

Shared Preferences is a way Android can store a small amount of data that is private to the application. The shared preferences data will persist even after the application ends. The SharedPreferences class allows persistent storage of key-value pairs of primitive data types (boolean, float, int, long, string).
  1. Shared preferences data is typically written during the Pause phase of the activity life lifecycle by:
    • Call edit() to get a shared preferences editor.
    • Add values to the editor with methods such as putString and putInt.
    • Commit the added values with commit().

  2. Shared Preferences data is usually retrieved during the Resume or Create phase of the activity life lifecycle with methods such as getString and getInt.
Spinners aka Drop Down Lists
Note: See Android Development - Spinners for a coding example of how to code a spinner.

Spinners are the Android name for Drop Down Lists(DDL). Spinners are data input controls which allows a quick way to select one value from a set of values. The spinner below was created using an XML layout file with the data stored in strings.xml. In the activity an event listener was coded for the spinner and the action after making a choice was coded by overriding the OnItemSelected class.

spinner

List Views Activity, List Activity, Adapters
Note: See Android Development - List Views for a coding example of how to code a list view by overriding the ListActivity class.

List views are activities that display items in a vertical scrolling list. The list items are automatically inserted in to the list using an Adapter. The adapter pulls content from a source such as an array or a database query. List views can be customized to fit various needs. List views can be created by overriding the Activity class with a new class. List views can also be created by overriding the Activity class with the predefined ListActivity class. ListActivity provides shortcut methods to simplify coding. The list view below was created by overriding ListActivity and using two XML layout files.

listview

Menus Context Menus, Options Menus, Sub Menus

Note: See Android Development - Menus for a coding example of how to code an options menu.

Menus can be defined in either an XML file or in the application code. The Android Developers website recommends defining menus in XML files. Android supports three types of menus:

  1. Options Menu (Action Bar) - contains menu items for an application, which appears when the user touches the MENU button.

    An options menu is where actions that have a global impact should be placed. Such as: Search, Settings, About, etc.

    In API 10 or lower the option menu appears at the bottom of the screen when the user presses the Menu button. In API 11 and higher the options menu is available in the action bar. The action bar is a dedicated area at the top that usually persists throughout the application.

    The option menu supports 1 to 6 options. If more than 6 options are needed, then the 6th option button is used as a "More" option that calls an option sub menu (see Sub Menu below).

  2. Context Menu - is a floating list of menu items that appears when a long-press is performed on an element.

    Context Menus provide actions relating to the selected content. Context menus do not support item shortcuts or icons.

  3. Sub Menu - is a nested menu that can be added to any type of menu (Options or Context).

    Unlike context menus, sub menus can can be invoked by any event, just a long-press. Sub menus do not support item icons or nested sub menus.

The following Options Menu was created by using the MenuInflator class inside the onCreateOptionsMenu method. The action for a menu item selection was coded in the onOptionsItemSelected Method.

menu


WebViews Display HTML with WebKit
Note: See Android Development - WebViews for a coding example of how to code a web view.

The WebView class will display web pages (HTML). WebView uses the WebKit rendering engine and can optionally include methods for many of the usual capabilities of a web browser. If the WebView class is used to access the Internet, you must add the INTERNET permissions to the Android Manifest file. However if you want to access the Internet, it is probably better to invoke a web browser application with a URL intent, as shown below:


Uri uri = Uri.parse("http://www.kcshadow.net"); 
Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
startActivity(intent);        
  
Using WebView for Help Screen

A common use of the WebView class is to display local HTML in the application, such as in a Help screen. Below a web view created with the WebView class that reads a local HTML file.

webview


Custom Views Creating Views Programmatically and Combining Views
Note: See Android Development - Custom Views for a coding example of how to code a custom view for drawing on a canvas.

The Android API has a large set of View classes for displaying various types of data. However sometimes the application has needs that are not met by the built-in views In those cases a custom view can be created by overriding one of the existing Views classes or by overriding the View class itself. View objects draw themselves in the onDraw() method. A Canvas object is created as a drawing area for graphics methods (drawLine, drawPoint, drawText, etc.). Custom views can be created in layout files (XML) or programmatically.

Below is an example of creating two views programmatically and joining them together in one activity. One view contains a canvas and the other view contains an exit button.

custom view


Top | Software Stack | Terminology | XML Files | Layouts | Activities | Fragments | Intents | Intent Extras | Activity State | Shared Preferences | Spinners | List Views | Menus | WebViews | Custom Views
Java API Specifications | Eclipse