0% found this document useful (0 votes)
25 views141 pages

Unit I

The document provides an overview of Android as a mobile application development platform, detailing its history, structure, and key components. It discusses the Open Handset Alliance, the Android software stack, and the tools necessary for development, including the Android SDK and Eclipse IDE. Additionally, it covers the fundamental building blocks of Android applications, such as Activities, Intents, and ContentProviders, along with a simple tutorial for creating a basic Android project.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views141 pages

Unit I

The document provides an overview of Android as a mobile application development platform, detailing its history, structure, and key components. It discusses the Open Handset Alliance, the Android software stack, and the tools necessary for development, including the Android SDK and Eclipse IDE. Additionally, it covers the fundamental building blocks of Android applications, such as Activities, Intents, and ContentProviders, along with a simple tutorial for creating a basic Android project.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 141

Mobile Application

Development
with Android
Introduction

What is Android?
• A software platform and operating system for mobile devices

• Based on the Linux kernel

• Developed by Google and later the Open Handset Alliance (OHA)

• Allows writing managed code in the Java language

Unveiling of the Android platform was announced on 5 November 2007


with the founding of OHA
History of Android
• Google acquired the startup company Android Inc. in 2005 to
start the development of the Android Platform. The key
players at Android Inc. included Andy Rubin, Rich Miner, Nick
Sears, and Chris White.
• In late 2007, a group of industry leaders came together around
the Android Platform to form the Open Handset Alliance
(http://www.openhandsetalliance.com).
• The Android SDK was first issued as an “early look” release in
November 2007.
• In September 2008 T-Mobile announced the availability of the
T-Mobile G1, the first smart phone based on the Android
Platform.
• A few days after that, Google announced the availability of
Android SDK Release Candidate 1.0.
• In October 2008, Google made the source code of the Android
Platform available under Apache’s open source license.
History of Android
What is Open Handset Alliance?
• Quoting from www.OpenHandsetAlliance.com page
• “… Open Handset Alliance™, a group of 47
technology and mobile companies have come
together to accelerate innovation in mobile and offer
consumers a richer, less expensive, and better mobile
experience.
• Together they have developed Android™, the first
complete, open, and free mobile platform.
• They are committed to commercially deploy handsets
and services using the Android Platform. “
Introduction
What is the Open Handset Alliance (OHA)?

→ It's a consortium of several companies

Google Android
Open Handset Alliance Members
Phones

HTC G1,
Droid, Motorola Droid (X)
Tattoo

Suno S880 Samsung Galaxy Sony Ericsson

@2010 Mihail L. Sichitiu 8


Tablets

Velocity Micro Cruz Gome FlyTouch Acer beTouch

Toshiba Android Cisco Android Tablet


Dawa D7 SmartBook

@2010 Mihail L. Sichitiu 9


Platform
Hardware

Android is not a single piece of hardware; it's a complete, end-


to-end software platform that can be adapted to work on any
number of hardware configurations. Everything is there, from the
bootloader all the way up to the applications.

Google Android
Android’s Context: Mobile Market Player$
Stakeholders:
• Mobile network operators want to
lock down their networks,
controlling and metering traffic.
• Device manufacturers want to
differentiate themselves with
features, reliability, and price
points.
• Software vendors want complete
access to the hardware to deliver
cutting-edge applications.
The Maturing Mobile Experience

• Tomorrow?
The Maturing Mobile Experience
Android vs. Competitors
Platform - The Android Software Stack

@2010 Mihail L. Sichitiu 15


Android S/W Stack - Application

• Android provides a set of core applications:


 Email Client
 SMS Program
 Calendar
 Maps
 Browser
 Contacts
 Etc
• All applications are written using the Java language.
@2010 Mihail L. Sichitiu 16
Android S/W Stack – App Framework

• Most of the application framework accesses these


core libraries through the Dalvik VM, the
gateway to the Android Platform

@2010 Mihail L. Sichitiu 17


Android S/W Stack –
App Framework (Cont)
Feature Role

View Used to build an application, including lists, grids, text


System boxes, buttons, and embedded web browser

Content Enabling applications to access data from other


Provider applications or to share their own data

Resource Providing access to non-code resources (localized string


Manager , graphics, and layout files)

Notification Enabling all applications to display customer alerts in the


Manager status bar

Activity Managing the lifecycle of applications and providing


Manager a common navigation back stack

@2010 Mihail L. Sichitiu 18


Location Manager
Notification Manager
Notification Manager
• How background app interact with users

• Consistent notification presentation


View System
View System
Android S/W Stack - Libraries

• Including a set of C/C++ libraries used by components


of the Android system
• Exposed to developers through the Android
application framework

@2010 Mihail L. Sichitiu 24


Android S/W Stack - Libraries
• The media libraries are based on PacketVideo’s
(http://www.packetvideo.com/) OpenCORE. These libraries are
responsible for recording and playback of audio and video formats.
A library called Surface Manager controls access to the display
system and supports 2D and 3D.
• The WebKit library is responsible for browser support; it is the same
library that supports Google Chrome and Apple Inc.’s Safari.
The FreeType library is responsible for font support.
SQLite (http://www.sqlite.org/) is a relational database that is available
on the device itself. SQLite is also an independent open source effort
for relational databases and not directly tied to Android. You can
acquire and use tools meant for SQLite for Android databases as
well.
Android S/W Stack - Runtime

• Core Libraries
Providing most of the functionality available in the
core libraries of the Java language
APIs
Data Structures
Utilities
File Access
Network Access
Graphics
Etc @2010 Mihail L. Sichitiu 26
The Dalvik runtime is optimised for
mobile applications

Run multiple VMs efficiently

Each app has its own VM

Minimal memory footprint


Bruce Scharlau, University of Aberdeen,
2010
Android S/W Stack – Runtime (Cont)
• Dalvik Virtual Machine (Cont)
Executing the Dalvik Executable (.dex) format
.dex format is optimized for minimal memory footprint.
Compilation

Relying on the Linux Kernel for:


Threading
Low-level memory management

@2010 Mihail L. Sichitiu 28


Android applications are compiled to
Dalvik bytecode
Write app in Java
Compiled in Java

Transformed to Dalvik bytecode

Loaded into Dalvik VM

Linux OS

Bruce Scharlau, University of Aberdeen,


2010
Android S/W Stack – Linux Kernel

 Relying on Linux Kernel 2.6 for core system services

 Memory and Process Management

 Network Stack

 Driver Model

 Security
• The supplied device drivers include Display, Camera, Keypad,
WiFi, Flash Memory, Audio, and IPC (interprocess
communication).
 Providing an abstraction layer between the H/W and the rest of the
S/W stack
@2010 Mihail L. Sichitiu 30
Platform
Network Connectivity

It supports wireless communications using:

 GSM mobile-phone technology

 3G

 Edge

 802.11 Wi-Fi networks

Google Android
Software development
Development requirements

• Java

• Android SDK

Google Android
Software development
IDE and Tools
Android SDK
• Class Library
• Developer Tools
• Emulator and System Images
• Documentation and Sample Code

Eclipse IDE + ADT (Android Development Tools)


• Reduces Development and Testing Time
• Makes User Interface-Creation easier
• Makes Application Description Easier

Google Android
Advantages

Here are a few other advantages Android offers you as a developer:

• The Android SDK is available for Windows, Mac and Linux, so you don’t
need to pay for new hardware to start writing applications.
• An SDK built on Java. If you’re familiar with the Java programming language,
you’re already halfway there.
• By distributing your application on Android Market, it’s available to hundreds of
thousands of users instantly. You’re not just limited to one store, because there are
alternatives, too. For instance, you can release your application on your own
blog. Amazon have recently been rumoured to be preparing their own
Android app store also.
• As well as the technical SDK documentation, new resources are being
published for Android developers as the platform gains popularity among both
users and developers.

Google Android
Application Building Blocks

• Activity
• IntentReceiver
• Service
• ContentProvider
Activities

• Typically correspond to one UI screen


• But, they can:
– Be faceless
– Be in a floating window
– Return a value
IntentReceivers

• Components that respond to broadcast ‘Intents’


• Way to respond to external notification or alarms
• Apps can invent and broadcast their own Intent
Intents

• Think of Intents as a verb and object; a


description of what you want done
– E.g. VIEW, CALL, PLAY etc..
• System matches Intent with Activity that can best
provide the service
• Activities and IntentReceivers describe what
Intents they can service
Intents Photo
Gallery
Home

Picasa

Contacts

“Pick photo”
GMail

Chat

Blogger
Blogger
Services

• Faceless components that run in the background


– E.g. music player, network download etc…
ContentProviders

• Enables sharing of data across applications


– E.g. address book, photo gallery
• Provides uniform APIs for:
– querying
– delete, update and insert.
• Content is represented by URI and MIME type
Android Introduction
Hello World

1
Tutorial
 http://developer.android.com/resources/t
utorials/hello-world.html
 http://mobiforge.com/developing/story/ge
tting-started-with-android-
development?dm_switcher=true

Android
Politeknik Elektronika Negeri Surabaya
2
Create a New Android Project
 From Eclipse, select File > New > Android
Project.
 Fill in the project details with the following
values:
 Project name: HelloAndroid
 Application name: Hello, Android
 Package name: com.example.helloandroid (or
your own private namespace)
 Create Activity: HelloAndroid
Click Finish
Android
Politeknik Elektronika Negeri Surabaya
3
Create a New
Android Project

Android
Politeknik Elektronika Negeri Surabaya
4
Create a New Android Project
 Project name - the name of the project
 Package name - the name of the package. This
name will be used as the package name in your
Java files. Package name must be fully qualified.
The convention is to use your company's domain
name in reverse order
 Activity name - the name of the activity in your
Android application. In Android, think of an
activity as a screen containing some actions,
hence the name "activity"
 Application name - the user-friendly name of the
application that will be displayed in the
Applications tab of the Android UI

Android
Politeknik Elektronika Negeri Surabaya
5
Package Content
All source code here Java code for our activity

All non-code Generated Java code


resources Helps link resources to
Java code

Images Layout of the activity

Strings used in the


program

Android Manifest
Android
Politeknik Elektronika Negeri Surabaya
6
the various fields when create a new
Android project
 First, the src folder contains your Java source files. The HelloAndroid.java
file is the source file for the HelloAndroid activity you specified when you
created the project earlier.

 The R.java file is a special file generated by the ADT to keep track of all
the names of views, constants, etc, used in your Android project. You
should not modify the content of this file as its content is generated
automatically by the ADT.

 The Android Library contains a file named android.jar. This file contains all
the classes that you would use to program an Android application.

 The res folder contains all the resources used by your Android application.
For example, the drawable folder contains a png image file that is used as
the icon for your application. The layout folder contains an XML file used to
represent the user interface of your Android application. The values folder
contains an XML file used to store a list of string constants.

 The AndroidManifest.xml file is an application configuration file that


contains detailed information about your application, such as the number
of activities you have in your application, the types of permissions your
application needs, the version information of your application, and so on.
Android
Politeknik Elektronika Negeri Surabaya
7
HelloAndroid.java
 Open the HelloAndroid.java file, located inside HelloAndroid > src
> com.example.helloandroid)

package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;

public class HelloAndroid extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

Android
Politeknik Elektronika Negeri Surabaya
8
HelloAndroid.java
 The basic unit of an Android application is an Activity.
 An Activity displays the user interface of your application,
which may contain widgets like buttons, labels, text boxes,
etc
 When the activity is loaded, the onCreate() event handler is
called.
 The activity loads its UI from the XML file named main.xml.
This is represented by the constant named R.layout.main
(generated automatically by the Eclipse as you save your
project).
 If you examine the main.xml file located in the res/layout
folder

Android
Politeknik Elektronika Negeri Surabaya
9
Run the Application
 The Eclipse plugin makes it easy to run your applications:
 Select Run > Run.
 Select "Android Application".

Android
Politeknik Elektronika Negeri Surabaya
10
/res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>

Android
Politeknik Elektronika Negeri Surabaya
11
XML attributes
 xmlns:android
This is an XML namespace declaration that tells the Android
tools that you are going to refer to common attributes
defined in the Android namespace. The outermost tag in
every Android layout file must have this attribute.
 android:id
This attribute assigns a unique identifier to the TextView
element. You can use the assigned ID to reference this
View from your source code or from other XML resource
declarations.
 android:layout_width
This attribute defines how much of the available width on
the screen this View should consume. In this case, it's the
only View so you want it to take up the entire screen, which
is what a value of "fill_parent" means.
Android
Politeknik Elektronika Negeri Surabaya
12
XML attributes
 android:layout_height
This is just like android:layout_width, except that it refers
to available screen height.

 android:text
This sets the text that the TextView should display. In this
example, you use a string resource instead of a hard-coded
string value. The hello string is defined in the
res/values/strings.xml file. This is the recommended
practice for inserting strings to your application, because it
makes the localization of your application to other
languages graceful, without need to hard-code changes to
the layout file.

Android
Politeknik Elektronika Negeri Surabaya
13
/res/values/strings.xml
 In Android, the UI of each activity is represented using various
objects known as Views. You can create a view using code, or
more simply through the use of an XML file.
 In this case, the UI Is represented using an XML file.
 The <TextView> element represents a text label on the screen
while the <LinearLayout> element specifies how views should be
arranged.
 Notice that the <TextView> element has an attribute named
android:text with its value set to "@string/hello".
 The @string/hello refers to the string named hello defined in the
strings.xml file in the res/values folder.

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


<resources>
<string name="hello">Hello World, HelloAndroid!</string>
<string name="app_name">HelloAndroid</string>
</resources>

Android
Politeknik Elektronika Negeri Surabaya
14
Modify strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello, Android! I am a string
resource!</string>
<string name="app_name">Hello, Android</string>
</resources>

Android
Politeknik Elektronika Negeri Surabaya
15
Run it !

Android
Politeknik Elektronika Negeri Surabaya
16
Modify the main.xml
 Let's now modify the main.xml file. Add the following <Button> element:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/btnClickMe"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click Me!"
/>
</LinearLayout>

Android
Politeknik Elektronika Negeri Surabaya
17
Run it !

Android
Politeknik Elektronika Negeri Surabaya
18
Construct UI
package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
}
}

Android
Politeknik Elektronika Negeri Surabaya
19
Run it

Android
Politeknik Elektronika Negeri Surabaya
20
R class
 In Eclipse, open the file named R.java (in the gen/ [Generated Java Files] folder).
 The R.java file is a special file generated by the ADT to keep track of all the names of
views, constants, etc, used in your Android project. You should not modify the
content of this file as its content is generated automatically by the ADT

package com.example.helloandroid;

public final class R {


public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int textview=0x7f050000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}

Android
Politeknik Elektronika Negeri Surabaya
21
AndroidManifest.xml
 The AndroidManifest.xml file is an application configuration file
that contains detailed information about your application, such as
the number of activities you have in your application, the types of
permissions your application needs, the version information of
your application, and so on.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloandroid"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HelloAndroid"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Android
Politeknik Elektronika Negeri Surabaya
22
Part 2-a

Android Environment
SDK
Victor Matos
Cleveland State University

Notes are based on:


Android Developers
http://developer.android.com/index.html

1
2A. Android Environment: Eclipse & ADT

The Android Development Tools (ADT) plugin for Eclipse adds extensions
to the Eclipse IDE.
It allows you to create and debug Android applications easier and faster.

Advantages
1. It gives you access to other Android development tools from inside the
Eclipse IDE. For example:
• take screenshots,
• Debug / set breakpoints, and
• view thread and process information directly from Eclipse.
2. It provides a New Project Wizard, which helps you quickly create and
set up all of the basic files you'll need for a new Android application.
3. It automates and simplifies the process of building your Android
application.
4. It provides an Android code editor that helps you write valid XML for
your Android manifest and resource files.
5. It will export your project into a signed APK, which can be distributed
to users.

2
2A. Android Environment: Eclipse & ADT

Typical Layout of the Eclipse IDE for Android Development

3
2A. Android Environment: Eclipse & ADT

Typical Layout of the Eclipse IDE for Android Development


(details…)

Android SDK and AVD Manager


New Android Project

DDMS Perspective
Dalvik Debugging Monitoring System

4
2A. Android Environment: Eclipse & ADT
SETUP
Download the Android SDK – Installing on Windows, Linux, Mac OS
This page is taken from http://developer.android.com

If you're already using the Android SDK, you should update to the latest tools or platform using
the Android SDK and AVD Manager, rather than downloading a new SDK starter package.

Windows installer_r08-windows.exe
Mac OS X (intel) android-sdk_r08-mac_86.zip
Linux (i386) android-sdk_r08-linux_86.tgz

Here's an overview of the steps you must follow to set up the Android SDK:

1. Prepare your development computer and ensure it meets the system requirements.
2. Install the SDK starter package from the table above. (If you're on Windows, download the
installer for help with the initial setup.)
3. Install the ADT Plugin for Eclipse (if you'll be developing in Eclipse).
4. Add Android platforms and other components to your SDK.
5. Explore the contents of the Android SDK (optional).

To get started, download the appropriate package from the table above, then read the
guide to Installing the SDK.
5
2A. Android Environment: Eclipse & ADT

Installing the SDK (Link: http://developer.android.com/sdk/installing.html)

This page describes how to install the Android SDK and set up your development
environment for the first time.

Updating?
If you already have an Android SDK, use the Android SDK and AVD Manager tool
to install updated tools and new Android platforms into your existing
environment.

Step 1. Preparing Your Development Computer

1. Make sure you have already installed the most recent JDK.

2. Make sure you have Eclipse installed on your computer (3.4 or newer is
recommended). Eclipse is available from: http://www.eclipse.org/downloads/
(For Eclipse 3.5 or newer, the "Eclipse Classic" version is recommended)

6
2A. Android Environment: Eclipse & ADT

Step 2. Downloading the SDK Starter Package


The SDK starter package is not a full development environment—it includes only
the core SDK Tools, which you can use to download the rest of the SDK
components (such as the latest Android platform).

If you downloaded the Windows installer (.exe file), run it now to install the SDK
Tools into a default location (which you can modify, usually the folder is:
c:/your-chosen-path/android-sdk-windows

Make a note of the name and location of the SDK directory on your system—you
will need to refer to the SDK directory later, when setting up the ADT plugin and
when using the SDK tools from command line.

Step 3. Installing the ADT Plugin for Eclipse


Android offers a custom plugin for the Eclipse IDE, called Android Development
Tools (ADT). This is the recommended platform. You may want to first read
Installing the ADT Plugin for step-by-step installation instructions, then return
here to continue the last step in setting up your Android SDK.
7
2A. Android Environment: Eclipse & ADT

Step 4. Adding Platforms and Other Components


You will use the Android SDK and AVD Manager (a tool included in the SDK starter
package) to download essential SDK components into your development
environment.

If you used the Windows installer, when you complete the installation wizard, it
will launch the Android SDK and AVD Manager with a default set of platforms and
other components selected for you to install. Simply click Install to accept the
recommended set of components and install them.

You can launch the Android SDK and AVD Manager in one of the following ways:
From within Eclipse, select Window > Android SDK and AVD Manager.
On Windows, double-click the SDK Manager.ext file at the root of the Android
SDK directory.

On Mac or Linux, open a terminal and navigate to the tools/ directory in the
Android SDK, then execute: android

8
2A. Android Environment: Eclipse & ADT

Step 4. Adding Platforms and Other Components (cont.)


To download components, use the graphical UI of the Android SDK and AVD Manager.
To begin with choose only the latest version of Android (include documentation,
samples and USB driver) (Warning: this process is slow…)

Figure 1. The Android SDK and AVD Manager's Available Packages panel, which shows
the SDK components that are available for you to download into your environment.
9
2A. Android Environment: Eclipse & ADT

Installing the Eclipse ADT Plugin


(Link: http://developer.android.com/sdk/eclipse-adt.html#installing)

To simplify ADT setup, it is recommend installing the Android SDK prior to installing ADT.

Eclipse 3.5 (Galileo) and 3.6 (Helios)


1. Start Eclipse, then select Help > Install New Software....
2. Click Add, in the top-right corner.
3. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and
the following URL for the Location:
https://dl-ssl.google.com/android/eclipse/
Note: If you have troubles try using "http" instead of "https”
Click OK.
4. In the Available Software dialog, select the checkbox next to Developer Tools and
click Next.
5. In the next window, you'll see a list of the tools to be downloaded. Click Next.
6. Read and accept the license agreements, then click Finish.
7. When the installation completes, restart Eclipse.
10
2A. Android Environment: Eclipse & ADT

Configuring the ADT Plugin

The next step is to modify your ADT preferences in Eclipse to point to the
Android SDK directory:

1. Select Window > Preferences... to open the Preferences panel


(Mac OS X: Eclipse > Preferences).
1. Select Android from the left panel.
2. For the SDK Location in the main panel, click Browse... and locate
your downloaded SDK directory (c:/path/android-sdk-windows)
3. Click Apply, then OK.

Done!

11
2A. Android Environment: Eclipse & ADT

Creating an Android Virtual Device (AVD)

Android Virtual Devices (AVDs) are configurations of emulator options that let
you better model an actual device.
1. In Eclipse, choose Window > Android SDK and AVD Manager.
2. Select Virtual Devices in the left panel.
3. Click New.
4. The Create New AVD dialog appears.
5. Type the name of the AVD, such as “AVD23API9".
6. Choose a target (such as “Android 2.3 – API Level9”).
7. Optionally specify any additional settings
(SD, camera, trackball, ….) YES to all.
8. Click Create AVD.

12
2A. Android Environment: Eclipse & ADT

Testing the Emulator

Android Virtual Devices (AVDs) are configurations of emulator options that let
you better model an actual device.
1. In Eclipse, choose Window > Android SDK and AVD Manager.
2. Select Virtual Devices in the left panel.
3. Click on an AVD
4. Click Start.

13
2A. Android Environment: Eclipse & ADT

A Final Step

This seems to be a transitional issue, and may go away in future releases. For
now, update the system’s PATH variable to recognize two folders inside your
android-sdk-winwows. The first is: tools and the second is platform-tools.

1. Windows > Start > Control Panel > System > Advanced > Environment
Variables > System Variables > PATH > Edit
2. Add references to the sub-folders mentioned above. In this example:
c:\android-sdk-windows\tools;C:\android-sdk-windows\platform-tools;
3. OK

14
Android Setup Videos
Appendix. Web resources available at
http://www.hometutorials.com/google-android.html
Five videos, a bit older (SDK1.0) but useful nonetheless.

1. How to setup Java.


2. How to install Eclipse IDE
3. Application development: “Hello World” using Eclipse
+ Android

15
Android Setup Tutorial
MAC OS Users
1. In a terminal window send the command: sudo su. You will act as the superuser.

1. Enter superuser’s password. After accepted, you will issue commands from a shell line.

2. Locate the file .profile and edit (pico, vi,…) its path contents as follows:
export PATH="/Users/myfolder/android-sdk-mac_86 3/tools":$PATH

where "/Users/myfolder/android-sdk-mac_86 3/tools" (including the quotes) is the location


of the /tools directory in our Android SDK folder.

16
Android Setup Tutorial
Appendix. Install Java
1. Go to http://developers.sun.com/downloads/
2. Expand choice Java SE.
3. Click on: Java SE (JDK) 6
4. From the list of choices select the most recent Java SE JDK (Update 14 in our case).
5. Click on the Download button

17
Android Setup Tutorial
Appendix. Install Java
1. On the next screen select Platform (Windows) and accept license agreement.
2. Hit the Continue button.
3. Check box: Java SE Development Kit 6u14 and click on the download (arrow) symbol
4. Save file to c:\

18
Android Setup Tutorial
Appendix. Install Java
5. Execute the downloaded file: jdk-6u14-windows-i586.exe
6. Click on Accept button to agree on licensing.
7. Note the Java folder location. Click on Next to complete installation.

19
Android Setup Tutorial
Appendix. Install Eclipse IDE
Eclipse is a multi-language software development
platform comprising an IDE and a plug-in system to
extend it. It can be used to develop applications in Java
and, by means of the various plug-ins, in other
languages (from Wikipedia)

1. Go to http://www.eclipse.org/downloads/.
2. Download the current version (Galileo at the time of
writing) and save it to drive C:\.
3. Unzip the compress file to your hard drive (c:\eclipse)
4. For convenience create a Shortcut to eclipse.exe and
place it on your Desktop.

20
Android Setup Tutorial
Appendix. Install Eclipse IDE

1. Launch eclipse application.


2. Create a folder to be your workspace

21
Android Setup Tutorial
Appendix. Creating an Android Project (made for 1.5)
Reference: http://developer.android.com/guide/developing/eclipse-adt.html

Hola Mundo

22
Android Setup Tutorial
Creating an Android Project
To create a new project:
1. Start Eclipse
2. Select File > New > Project.
3. Select Android > Android Project,
and click Next.
4. Enter Project name: AndHolaMundo.
5. Select Target Android 1.5.
6. Application name: Hola.
7. Package name: cis493.demo.
8. Create Activity: HolaMundo.
9. Min SDK Version: 3.
10. Click Finish.

23
Android Setup Tutorial
Creating an Android Project
Once you complete the New Project Wizard, ADT creates the following folders and
files in your new project:

• src/ Includes your stub Activity Java file. All other Java files for your application
go here.
• <Android Version>/ (e.g., Android 1.5/) Includes the android.jar file that your
application will build against.
• gen/ This contains the Java files generated by ADT, such as your R.java file and
interfaces created from AIDL files.
• assets/ This is empty. You can use it to store raw asset files.
• res/ A folder for your application resources, such as drawable files, layout files,
string values, etc.
• AndroidManifest.xml The Android Manifest for your project.
• default.properties This file contains project settings, such as the build target.

24
Android Setup Tutorial
Creating an Android
Project
Once you complete the New
Project Wizard, ADT creates the
following folders and files in your
new project:

25
Android Setup Tutorial
Creating an Android Project

26
Android Setup Tutorial
Creating an Android Project - Debugging

27
Android Setup Tutorial
Creating an Android Project
package matos.demo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class HolaMundo extends Activity {


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for (int i=0; i<3; i++){
Toast.makeText(getApplicationContext(), i + " Hola Mundo", 1).show();
}
Toast.makeText(getApplicationContext(), " Adios", 1).show();
}
}

28
Android Setup Tutorial
Creating an Android Project

29
Android Setup Tutorial

Questions ?

30
Android Setup Tutorial
Summary of Android On-line Installation Resources
0. JAVA
http://www.dailymotion.com/video/x77uqg_google-android-emulator-tutorial-tr_tech

1. ECLIPSE
http://www.dailymotion.com/related/x77v5t_google-android-eclipse-adt-tutorial_tech/video/x77usr_google-android-eclipse-tutorial-tra_tech

2. ANDROID-SDK
Android ADT Eclipse Plug-in link: https://dl-ssl.google.com/android/eclipse/
http://www.dailymotion.com/related/x77v5t_google-android-eclipse-adt-tutorial_tech/video/x77uou_google-android-sdk-emulator-tutoria_tech

3. ECLIPSE-PLUGIN
http://www.dailymotion.com/related/x77usr_google-android-eclipse-tutorial-tra_tech/video/x77v5t_google-android-eclipse-adt-
tutorial_tech?from=rss

4. HELLO WORLD TUTORIAL


http://www.dailymotion.com/video/x77v6w_google-android-apps-tutorial-traini_tech

5. DROID_DRAW
http://www.droiddraw.org

6. MAKING SDCARD (Video, blogs)


http://www.anddev.org/emulating_a_sd-card-t263.html
http://groups.google.com/group/android-developers/browse_thread/thread/9d068936b43c5f27
http://www.anddev.org/problem_pushing_files_onto_sdcard-t2467.html

7. Three GOOD videos from Google (Architecture, Interprocess Comm, APIs)


1. http://www.youtube.com/watch?v=QBGfUs9mQYY&eurl=http://developerlife.com/theblog/?p=454
2. http://www.youtube.com/watch?v=fL6gSd4ugSI&feature=related
3. http://www.youtube.com/watch?v=MPukbH6D-lY&feature=related

8. More APPs (Google President, HelloWorld, PhoneLocator)


http://www.youtube.com/watch?v=1FJHYqE0RDg&feature=channel
http://www.youtube.com/watch?v=I6ObTqIiYfE&feature=channel
http://www.helloandroid.com/taxonomy/term/29
31
Android Setup Tutorial

Appendix A.
Android Virtual Devices
An AVD tells the emulator what kind of device it is suppose to impersonate.
Currently there are a few of these targets, such as:

Target Description
Level
4 Identifies an Android 1.6 device that has Google Maps support
[mostly all new Android devices after 2008]

9 Identifies an Android 2.3 device that has Google Maps support


[mostly all new Android devices after 2010+ ]

32
Android Setup Tutorial
Appendix A. Cont
Android SDK Targets (2.x and newer versions)
You may use the UI app to inspect available components and download target platforms.

Downloading
This is a three-steps operation. First install the (empty) SDK shell as indicated above (download and
unzip). Second update the path system variable to include the path to: android-sdk-windows\tools.
Third: access the repository, select and download the specific targets.
How?
At the console prompt type in the command
C:> android

To add SDKs click on


Available Packages

Use the https://..... URL


(or equivalent but less secure
http://.... Locator )

Follow instructions to accept


Licensing. Wait (slow …)

33
Part 3

Android
Application’s Life Cycle
Victor Matos
Cleveland State University

Notes are based on:


Unlocking Android
by Frank Ableson, Charlie Collins, and Robi Sen.
ISBN 978-1-933988-67-2
Manning Publications, 2009.

Android Developers
http://developer.android.com/index.html
3. Android – Application's Life Cycle

Android Applications
An application consists of one or more components that are
defined in the application's manifest file. A component can be one
of the following:

1. An Activity
2. A Service
3. A broadcast receiver
4. A content provider

2
3. Android – Application's Life Cycle

Android Applications
1. Activity
An activity usually presents a single visual user interface from which a number of
actions could be performed.

Altough activities work together to form a cohesive user interface, each activity
is independent of the others.

Typically, one of the activities is marked as the first one that should be presented
to the user when the application is launched.

Moving from one activity to another is accomplished by having the current


activity start the next one through so called intents.

Reference: Friedger Müffke (friedger@openintents.org)


3
3. Android – Application's Life Cycle

Android Applications
2. Service

A service doesn't have a visual user interface, but rather runs in the background
for an indefinite period of time.

It's possible to connect to (bind to) an ongoing service (and start the service if it's
not already running).

While connected, you can communicate with the service through an interface
that the service exposes.

Reference: Friedger Müffke (friedger@openintents.org)


4
3. Android – Application's Life Cycle

Android Applications
3. Broadcast receiver

A broadcast receiver is a component that does nothing but receive and react to
broadcast announcements.

Many broadcasts originate in system code (eg. “you got mail“) but any other
applications can also initiate broadcasts.

Broadcast receivers do not display a user interface. However, they may start an
activity in response to the information they receive, or - as services do - they
may use the notification manager to alert the user.

Reference: Friedger Müffke (friedger@openintents.org)


5
3. Android – Application's Life Cycle

Android Applications
4. Content provider

A content provider makes a specific set of the application's data available to


other applications.

The data usually is stored in the file system, or in an SQLite database.

The content provider implements a standard set of methods that enable other
applications to retrieve and store data of the type it controls.

However, applications do not call these methods directly. Rather they use a
content resolver object and call its methods instead. A content resolver can talk
to any content provider; it cooperates with the provider to manage any
interprocess communication that's involved.
Reference: Friedger Müffke (friedger@openintents.org)
6
3. Android – Application's Life Cycle

Android Applications
Every Android application runs in its own process
(with its own instance of the Dalvik virtual machine).

Whenever there's a request that should be handled by a particular component,


• Android makes sure that the application process of the component is
running,
• starting it if necessary, and
• that an appropriate instance of the component is available, creating the
instance if necessary.

7
3. Android – Application's Life Cycle

Application’s Life Cycle

A Linux process encapsulating an Android application is created for the


application when some of its code needs to be run, and will remain
running until

1. it is no longer needed, OR
2. the system needs to reclaim its memory for use by other
applications.

8
3. Android – Application's Life Cycle

Application’s Life Cycle

An unusual and fundamental feature of Android is that an application


process's lifetime is not directly controlled by the application itself.

Instead, it is determined by the system through a combination of

1. the parts of the application that the system knows are running,
2. how important these things are to the user, and
3. how much overall memory is available in the system.

9
3. Android – Application's Life Cycle

Component Lifecycles
Application components have a lifecycle

1. A beginning when Android instantiates them to respond to


intents
2. An end when the instances are destroyed.
3. In between, they may sometimes be active or inactive, or -in the
case of activities- visible to the user or invisible.

Life as an Android Application:


Start Active / Inactive End
Visible / Invisible

10
3. Android – Application's Life Cycle

Activty Stack
• Activities in the system are managed as an activity stack.

• When a new activity is started, it is placed on the top of the


stack and becomes the running activity -- the previous
activity always remains below it in the stack, and will not
come to the foreground again until the new activity exits.

• If the user presses the Back Button the next activity on the
stack moves up and becomes active.

11
3. Android – Application's Life Cycle

Activity Stack
New Activity Running Activity

New Activity Back button pushed or


started running activity closed

Last Running
Activity
Activity n-1
Activity Stack ...
Previous Activity 3
Activities Removed to
Activity 2 free resources

Activity 1

12
3. Android – Application's Life Cycle

Life Cycle States

An activity has essentially


three states:

1. It is active or running
2. It is paused or
3. It is stopped .

13
3. Android – Application's Life Cycle

Life Cycle States


An activity has essentially three states:

1. It is active or running when it is in the foreground of the screen


(at the top of the activity stack for the current task).

This is the activity that is the focus for the user's actions.

14
3. Android – Application's Life Cycle

Life Cycle States


An activity has essentially three states:

2. It is paused if it has lost focus but is still visible to the user.

That is, another activity lies on top of it and that new activity either is
transparent or doesn't cover the full screen.

A paused activity is completely alive (it maintains all state and member
information and remains attached to the window manager), but can be
killed by the system in extreme low memory situations.

15
3. Android – Application's Life Cycle

Life Cycle States


An activity has essentially three states:

3. It is stopped if it is completely obscured by another activity.

It still retains all state and member information. However, it is no longer


visible to the user so its window is hidden and it will often be killed by
the system when memory is needed elsewhere.

16
3. Android – Application's Life Cycle

Application’s
Life Cycle

17
3. Android – Application's Life Cycle

Life Cycle Events


If an activity is paused or stopped, the system can drop it from memory
either by asking it to finish (calling its finish() method), or simply killing its
process.

When it is displayed again to the user, it must be completely restarted and


restored to its previous state.

As an activity transitions from state to state, it is notified of the change by


calls to the following protected transition methods:

void onCreate(Bundle savedInstanceState) void onPause()


void onStart() void onStop()
void onRestart() void onDestroy()
void onResume()

18
3. Android – Application's Life Cycle

Life Cycle Events


All of these methods are hooks that you can override to do appropriate
work when the state changes.

All activities must implement onCreate() to do the initial setup when the
object is first instantiated.

Many activities will also implement onPause() to commit data changes and
otherwise prepare to stop interacting with the user.

19
3. Android – Application's Life Cycle

Application’s Lifetime
The seven transition methods define the entire lifecycle of an activity.

The entire lifetime of an activity happens between the first call to


onCreate() through to a single final call to onDestroy().

An activity does all its initial setup of "global" state in onCreate(), and
releases all remaining resources in onDestroy().

20
3. Android – Application's Life Cycle

Visible Lifetime
The visible lifetime of an activity happens between a call to onStart() until a
corresponding call to onStop().

During this time, the user can see the activity on-screen, though it may not
be in the foreground and interacting with the user.

The onStart() and onStop() methods can be called multiple times, as the
activity alternates between being visible and hidden to the user.

Between these two methods, you can maintain resources that are needed
to show the activity to the user.

21
3. Android – Application's Life Cycle

Foreground Lifetime
The foreground lifetime of an activity happens between a call to
onResume() until a corresponding call to onPause().

During this time, the activity is in front of all other activities on screen and is
interacting with the user.

An activity can frequently transition between the resumed and paused


states — for example,
• onPause() is called when the device goes to sleep or when a new
activity is started,
• onResume() is called when an activity result or a new intent is
delivered.

22
3. Android – Application's Life Cycle

Life Cycle Methods

Method: onCreate()

• Called when the activity is first created.


• This is where you should do all of your normal static set up —
create views, bind data to lists, and so on.
• This method is passed a Bundle object containing the activity's
previous state, if that state was captured.
• Always followed by onStart()

23
3. Android – Application's Life Cycle

Life Cycle Methods

Method: onRestart()

• Called after the activity has been stopped, just prior to it being
started again.
• Always followed by onStart()

Method: onStart()

• Called just before the activity becomes visible to the user.


• Followed by onResume() if the activity comes to the foreground,
or onStop() if it becomes hidden.

24
3. Android – Application's Life Cycle

Life Cycle Methods

Method: onResume()

1. Called just before the activity starts interacting with the user.
2. At this point the activity is at the top of the activity stack, with
user input going to it.
3. Always followed by onPause().

25
3. Android – Application's Life Cycle

Life Cycle Methods

Method: onPause()

1. Called when the system is about to start resuming another


activity.
2. This method is typically used to commit unsaved changes to
persistent data, stop animations and other things that may be
consuming CPU, and so on.
3. It should do whatever it does very quickly, because the next
activity will not be resumed until it returns.
4. Followed either by onResume() if the activity returns back to the
front, or by onStop() if it becomes invisible to the user.
5. The activity in this state is killable by the system.

26
3. Android – Application's Life Cycle

Life Cycle Methods

Method: onStop()

1. Called when the activity is no longer visible to the user.


2. This may happen because it is being destroyed, or because
another activity (either an existing one or a new one) has been
resumed and is covering it.
3. Followed either by onRestart() if the activity is coming back to
interact with the user, or by onDestroy() if this activity is going
away.
4. The activity in this state is killable by the system.

27
3. Android – Application's Life Cycle

Life Cycle Methods

Method: onDestroy()

1. Called before the activity is destroyed.


2. This is the final call that the activity will receive.
3. It could be called either because the activity is finishing (someone
called finish() on it), or because the system is temporarily
destroying this instance of the activity to save space.
4. You can distinguish between these two scenarios with the
isFinishing() method.
5. The activity in this state is killable by the system.

28
3. Android – Application's Life Cycle

Life Cycle Methods


Killable States

• Activities on killable states can be terminated by the system at any


time after the method returns, without executing another line of the
activity's code.

• Three methods (onPause(), onStop(), and onDestroy()) are killable.

• onPause() is the only one that is guaranteed to be called before the


process is killed — onStop() and onDestroy() may not be.

• Therefore, you should use onPause() to write any persistent data


(such as user edits) to storage.

29
3. Android – Application's Life Cycle

Life Cycle Methods


As an aside…
Android Preferences

Preferences is a lightweight mechanism to store and retrieve key-value pairs of


primitive data types. It is typically used to store application preferences, such
as a default greeting or a text font to be loaded whenever the application is
started.

Call Context.getSharedPreferences() to read and write values.

Assign a name to your set of preferences if you want to share them with other
components in the same application, or use Activity.getPreferences() with no
name to keep them private to the calling activity.

You cannot share preferences across applications (except by using a content


provider). 30
LAYOUT
3. Android – Application's Life Cycle

Example
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"

Life Cycle android:id="@+id/myScreen"


android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff000000"
>
<TextView
Example android:layout_width="fill_parent"
android:layout_height="wrap_content"
The following application android:text="@string/hello"
/>
demonstrates some of <EditText
android:id="@+id/txtColorSelect"
the state transitioning android:hint="Background color (red, green, blue)"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
situations experienced in </EditText>
<TextView
the life-cycle of a typical android:id="@+id/txtToDo"
android:layout_width="fill_parent"
Android activity. android:layout_height="wrap_content"
android:background="#00000000">
<!-- transparent -->
</TextView>
<Button
android:text=" Finish "
android:id="@+id/btnFinish"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>

31
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 1
Package cis493.lifecycle

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.*;

//GOAL: show the following life-cycle events in action

//protected void onCreate(Bundle savedInstanceState);


//protected void onStart();
//protected void onRestart();
//protected void onResume();
//protected void onPause();
//protected void onStop();
//protected void onDestroy();

32
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 2
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myScreen = (LinearLayout) findViewById(R.id.myScreen);

txtToDo = (TextView) findViewById(R.id.txtToDo);


String msg = "Instructions: \n "
+ "0. New instance (onCreate, onStart, onResume) \n "
+ "1. Back Arrow (onPause, onStop, onDestroy) \n "
+ "2. Finish (onPause, onStop, onDestroy) \n "
+ "3. Home (onPause, onStop) \n "
+ "4. After 3 > App Tab > re-execute current app \n "
+ " (onRestart, onStart, onResume) \n "
+ "5. Run DDMS > Receive a phone call or SMS \n "
+ " (onRestart, onStart, onResume) \n "
+ "6. Enter some data - repeat steps 1-5 \n ";

txtToDo.setText(msg);

33
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 2
txtColorSelect = (EditText) findViewById(R.id.txtColorSelect);
// you may want to skip discussing the listener until later
txtColorSelect.addTextChangedListener(new TextWatcher(){
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
changeBackgroundColor(s.toString());
}
});

btnFinish = (Button) findViewById(R.id.btnFinish);


btnFinish.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
Toast.makeText(getApplicationContext(), "onCreate", 1).show();
}
34
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 3
@Override
protected void onPause() {
super.onPause();
saveDataFromCurrentState();
Toast.makeText(this, "onPause", 1).show();
}

@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(this, "onRestart", 1).show();
}

@Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "onResume", 1).show();
}

35
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 4
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
updateFromSavedState();
Toast.makeText(this, "onStart", 1).show();
}

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "onDestroy", 1).show();
}

@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(this, "onStop", 1).show();
} 36
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 5
protected void saveDataFromCurrentState() {
SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode);
SharedPreferences.Editor myEditor = myPrefs.edit();
myEditor.putString("myBkColor", txtColorSelect.getText().toString());
myEditor.commit();
}// saveDataFromCurrentState

protected void updateFromSavedState() {


SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode);

if ((myPrefs != null) && (myPrefs.contains("myBkColor"))) {


String theChosenColor = myPrefs.getString("myBkColor", "");
txtColorSelect.setText(theChosenColor);
changeBackgroundColor(theChosenColor);
}
}// UpdateFromSavedState

protected void clearMyPreferences() {


SharedPreferences myPrefs = getSharedPreferences(MYPREFSID, actMode);
SharedPreferences.Editor myEditor = myPrefs.edit();
myEditor.clear();
myEditor.commit();
} 37
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 6

private void changeBackgroundColor (String theChosenColor){


// change background color
if (theChosenColor.contains("red"))
myScreen.setBackgroundColor(0xffff0000);
else if (theChosenColor.contains("green"))
myScreen.setBackgroundColor(0xff00ff00);
else if (theChosenColor.contains("blue"))
myScreen.setBackgroundColor(0xff0000ff);
else {
//reseting user preferences
clearMyPreferences();
myScreen.setBackgroundColor(0xff000000);
}
}

38
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 8

/*
protected void onRestoreInstanceState(Bundle savedInstanceState)
This method is called after onStart() when the activity is being re-initialized
from a previously saved state.
The default implementation of this method performs a restore of any view state
that had previously been frozen by onSaveInstanceState(Bundle).
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Toast.makeText(getBaseContext(),
"onRestoreInstanceState ...BUNDLING",
Toast.LENGTH_LONG).show();
}

39
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 9

/*
protected void onSaveInstanceState(Bundle outState)

Called to retrieve per-instance state from an activity before being killed


so that the state can be restored in
onCreate(Bundle) or
onRestoreInstanceState(Bundle) (the Bundle populated by this method
will be passed to both).
This method is called before an activity may be killed so that when it comes
back some time in the future it can restore its state. For example, if activity B
is launched in front of activity A, and at some point activity A is killed to
reclaim resources, activity A will have a chance to save the current state of
its user interface via this method so that when the user returns to activity A,
the state of the user interface can be restored via:
onCreate(Bundle) or onRestoreInstanceState(Bundle).
*/

40
3. Android – Application's Life Cycle

Example: Life Cycle


Code: Life Cycle Demo. Part 10

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast.makeText(getBaseContext(),
"onSaveInstanceState ...BUNDLING",
Toast.LENGTH_LONG).show();
} // onSaveInstanceState

}//LyfeCicleDemo

41
3. Android – Application's Life Cycle

Example: Life Cycle


onCreate… onStart… onResume…

42
3. Android – Application's Life Cycle

Example: Life Cycle


onPause… onStop… onDestroy…

After pressing “Back Arrow”


43
3. Android – Application's Life Cycle

Example: Life Cycle


After After After
pressing “Home” re-executing AndLife2 “Back Arrow” or Finish

onSavedInstanceState > onRestart > onPause >


onPause > onStart > onStop >
onStop > onResume > onDestroy >

Preserving State Information


1. Enter data: “Hasta la vista!”
2. Click Home button
3. onSavedInstance > onPause > onStop
4. Read your SMS
5. Execute an instance of the application
6. onRestart > onStart > onResume
7. You see the data entered in step 1 End of Example
44
Application’s Life Cycle

Questions ?

45

You might also like