Tuesday, 3 January 2012

Activity Life Cycle of Android



Writing an application with a good understanding of the activity life cycle is critical to ensure that our application provides a seamless user experience and properly manages its resources.
Android application does not control its own process lifetimes. The Android run time manages the process of each application. While the run time handles the termination and management of an activity's process, the activity's state helps determine the priority of its parent application. The application priority, in turn, affects the likelihood that the run time will terminate it and the activities running within it.


Activity Stacks
The state of each activity is determined by its position on the activity stack. When a new activity starts, the current foreground screen is moved to the top of the stack. If the user navigates back using the Back button or the foreground activity is closed, the next activity on the stack moves up and becomes active.
An application's priority is influenced by its highest-priority activity. When the Android memory manager is deciding which application to terminate to free resources, it uses this stack to determine the priority of applications based on their activities.


Activity States
As activities are created and destroyed they move in and out of the stack. They transition through 4 states:
  • Active
    When an activity is at the top of the stack it is the visible, focused, foreground activity that is receiving user input. Android will attempt to keep it alive at all cost, killing activities further down the stack as needed, to ensure that it has the resources it needs. When another activity becomes active, this one will be paused.
  • Paused
    In some cases our activity will be visible but will not have focus. At this point it's paused. This state is reached if a transparent or not-full-screen activity is active in front of it. When paused, an activity is treated as if it were active. However, it doesn't receive user input events. In extreme cases, Android will kill a paused activity to recover resources for the active activity. When an activity becomes totally obscured, it is stopped.
  • Stopped
    When an activity isn't visible, it stops. The activity will remain in memory, retaining all state information. However, it is now a candidate for termination when the system requires memory elsewhere. When an activity stopped, it's important to save data and the current UI state. Once an activity exited or closed, it becomes inactive.
  • Inactive
    After an activity has been killed, and before it's been launched, it's inactive. Inactive activities have been removed from the activity stack and need to be restarted before they can be displayed and used.
State transitions are nondeterministic and are handled entirely by the Android memory manager. Android will start by closing applications that contain inactive activities, followed by those that are stopped. In extreme cases it will remove those that are paused.

Basic Building blocks of Android

Building blocks of Android



There are 4 building blocks in android:
1. Activity     
2. Service  
3. Content Provider
4. Broadcast Receiver


 Activity
           It is a component in which user can interact with User interface or screen.
 Represents the presentation layer of an Android application, e.g. a screen which the user sees. An Android application can have several activities and it can be switched between them during runtime of the application.

Service
       It perform background tasks without providing an UI. They can notify the user via the notification framework in Android. Each service class must have a corresponding <service> declaration in its package's AndroidManifest.xml.

ContentProvider
      Content providers store and retrieve data and make it accessible to all applications. They're the only way to share data across applications; there's no common storage area that all Android packages can access.. Android contains a SQLite DB which can serve as data provider.



BroadCast/Intent  Receiver
       A broadcast receiver is a class which extends BroadcastReceiver and which is registered as a receiver in an Android Application via the AndroidManifest.xml file.This class will be able to receive intents. Intents can be generated via the Context.sendBroadcast() method.The class BroadcastReceiver defines the method onReceive(). Only during this method your broadcast receiver object will be valid, afterwards the Android system will consider your object as no longer active. Therefore you cannot perform any asynchronous operation.

Architecture of Android

Architecture of Android

Applications-
        Android will ship with a set of core applications including an email client, SMS program, calendar, maps, browser, contacts, and others. All applications are written using the Java programming language.

Application framework
       By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more.

Libraries
    Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. Some of the core libraries are listed below:
System C library - a BSD-derived implementation of the standard C system library (libc), tuned for embedded Linux-based devices.
Media Libraries - based on PacketVideo's OpenCORE; the libraries support playback and recording of many popular audio and video formats, as well as static image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG.
Surface Manager - manages access to the display subsystem and seamlessly composites 2D and 3D graphic layers from multiple applications.
LibWebCore - a modern web browser engine which powers both the Android browser and an embeddable web view.
SGL - the underlying 2D graphics engine.
3D libraries - an implementation based on OpenGL ES 1.0 APIs; the libraries use either hardware 3D acceleration (where available) or the included, highly optimized 3D software rasterizer
FreeType - bitmap and vector font rendering.
SQLite - a powerful and lightweight relational database engine available to all applications.

TableLayout


TableLayout

TableLayout organizes content into rows and columns. The rows are defined in the layout XML, and the columns are determined automatically by Android. This is done by creating at least one column for each element. So, for example, if you had a row with two elements and a row with five elements then you would have a layout with two rows and five columns.
You can specify that an element should occupy more than one column using android:layout_span. This can increase the total column count as well, so if we have a row with two elements and each element has android:layout_span=”3″ then you will have at least six columns in your table.
By default, Android places each element in the first unused column in the row. You can, however, specify the column an element should occupy using android:layout_column.
Here is some sample XML using TableLayout.
<TableLayout 
         android:layout_width="fill_parent" 
         android:layout_height="fill_parent" 
         xmlns:android="http://schemas.android.com/apk/res/android">
         <TableRow>
                 <Button 
                  android:id="@+id/backbutton"
                  android:text="Back"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" />
         </TableRow>
         <TableRow>
                 <TextView
                  android:text="First Name"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_column="1" />
                 <EditText
                  android:width="100px"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" />
         </TableRow>
         <TableRow>
                 <TextView
                  android:text="Last Name"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_column="1" />
                 <EditText
                  android:width="100px"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" /> 
         </TableRow>
</TableLayout>
This is the result of that XML.

RelativeLayout


RelativeLayout lays out elements based on their relationships with one another, and with the parent container. This is arguably the most complicated layout, and we need several properties to actually get the layout we want.In relative layout each and every component’s ID is necessary.

Relative To Container

These properties will layout elements relative to the parent container.
  • android:layout_alignParentBottom – Places the bottom of the element on the bottom of the container
  • android:layout_alignParentLeft – Places the left of the element on the left side of the container
  • android:layout_alignParentRight – Places the right of the element on the right side of the container
  • android:layout_alignParentTop – Places the element at the top of the container
  • android:layout_centerHorizontal – Centers the element horizontally within its parent container
  • android:layout_centerInParent – Centers the element both horizontally and vertically within its container
  • android:layout_centerVertical – Centers the element vertically within its parent container

Relative To Other Elements

These properties allow you to layout elements relative to other elements on screen. The value for each of these elements is the id of the element you are using to layout the new element. Each element that is used in this way must have an ID defined using android:id=”@+id/XXXXX” where XXXXX is replaced with the desired id. You use “@id/XXXXX” to reference an element by its id. One thing to remember is that referencing an element before it has been declared will produce an error.
  • android:layout_above – Places the element above the specified element
  • android:layout_below – Places the element below the specified element
  • android:layout_toLeftOf – Places the element to the left of the specified element
  • android:layout_toRightOf – Places the element to the right of the specified element

Alignment With Other Elements

These properties allow you to specify how elements are aligned in relation to other elements.
  • android:layout_alignBaseline – Aligns baseline of the new element with the baseline of the specified element
  • android:layout_alignBottom – Aligns the bottom of new element in with the bottom of the specified element
  • android:layout_alignLeft – Aligns left edge of the new element with the left edge of the specified element
  • android:layout_alignRight – Aligns right edge of the new element with the right edge of the specified element
  • android:layout_alignTop – Places top of the new element in alignment with the top of the specified element
Here is a sample XML Layout
<RelativeLayout 
         android:layout_width="fill_parent" 
         android:layout_height="fill_parent" 
         xmlns:android="http://schemas.android.com/apk/res/android">
         <Button 
                 android:id="@+id/backbutton"
                 android:text="Back"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content" />
         <TextView
                 android:id="@+id/firstName"
                 android:text="First Name"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_below="@id/backbutton" />
         <EditText
                 android:width="100px"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_toRightOf="@id/firstName"
                 android:layout_alignBaseline="@id/firstName" />
         <TextView
                 android:id="@+id/lastName"
                 android:text="Last Name"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_below="@id/firstName" />
         <EditText
                 android:width="100px"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_toRightOf="@id/lastName"
                 android:layout_alignBaseline="@id/lastName" />
</RelativeLayout>
Here is the screen produced by that XML.

I wanted to show this to you because the first time I made a RelativeLayout I did exactly this and then looked at the screen and said, “Hang on a minute, that’s not what I wanted!” The problem here is that when Android draws the TextView lastName below the TextView firstName it only sets aside the space it needs for the TextView. Android only reads the Layout XML one time so it doesn’t know that an EditView is the next item and doesn’t plan for it. So when the EditView is drawn to the right of the TextView it only has the height of the TextView to work with so it overlaps the EditView above it. Here is the Layout XML I wrote to create the form the way it should look.
<RelativeLayout 
         android:layout_width="fill_parent" 
         android:layout_height="fill_parent" 
         xmlns:android="http://schemas.android.com/apk/res/android">
         <Button 
                 android:id="@+id/backbutton"
                 android:text="Back"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content" />
         <TextView
                  android:id="@+id/firstName"
                 android:text="First Name"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_below="@id/backbutton" />
         <EditText
                 android:id="@+id/editFirstName"
                 android:width="100px"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_toRightOf="@id/firstName"
                 android:layout_below="@id/backbutton"/>
         <EditText
                 android:id="@+id/editLastName"
                 android:width="100px"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_below="@id/editFirstName"
                 android:layout_alignLeft="@id/editFirstName"/>
         <TextView
                 android:id="@+id/lastName"
                 android:text="Last Name"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_toLeftOf="@id/editLastName"
                 android:layout_below="@id/editFirstName" /> 
</RelativeLayout>
You probably noticed that I had to rearrange the elements in the XML since, as I already mentioned, you cannot reference an element that has not already been laid out. Here is what the updated RelativeLayout produces.

LinearLayout


LinearLayout

LinearLayout organizes elements along a single line. You specify whether that line is verticle or horizontal using android:orientation. Here is a sample Layout XML using LinearLayout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="horizontal"
         android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     <Button 
         android:id="@+id/backbutton"
         android:text="Back"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" />
    <TextView
         android:text="First Name"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" />
    <EditText
         android:width="100px"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" />
    <TextView
         android:text="Last Name"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" />
    <EditText
         android:width="100px"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" /> 
</LinearLayout>
Here is a screenshot of the result of the above XML.

Here is a screenshot of the same XML except that the android:orientation has been changed to horizontal.

You might note that the EditText field at the end of the line has had its width reduced in order to fit. Android will try to make adjustments when necessary to fit items on screen. The last page of this tutorial will cover one method to help deal with this.
I mentioned on the first page that Layouts can be nested. LinearLayout is frequently nested, with horizontal and vertical layouts mixed. Here is an example of this.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:orientation="vertical"
         android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     <Button 
         android:id="@+id/backbutton"
         android:text="Back"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" />
    <LinearLayout
         android:orientation="horizontal"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content">
             <TextView
                  android:text="First Name"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" />
             <EditText
                  android:width="100px"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" />     
    </LinearLayout>
    <LinearLayout
         android:orientation="horizontal"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content">    
             <TextView
                  android:text="Last Name"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" />
             <EditText
                  android:width="100px"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" />
    </LinearLayout> 
</LinearLayout>
As you can see we have a Vertical LinearLayout whose children are a button, and two horizontal LinearLayouts. Each horizontal LinearLayout has two child controls. You should note that in the child LinearLayout elements I used android:layout_height=”wrap_content” instead of fill_parent. If I had used fill_parent the first name TextView and EditView would have taken all of the available space on the screen, and the Last Name would not have been displayed. Here is what this XML does display.