Android Application Development
-
Upload
ramesh-prasad -
Category
Documents
-
view
8.562 -
download
1
description
Transcript of Android Application Development
- 1.ANDROID APPLICATION DEVELOPMENT
Ramesh Prasad
2. INTRODUCTION
3. Android Devices
4. Mobile Operating System ?
5. A BRIEF HISTORY OF ANDROID
6. History
Android, Inc. was founded in Palo Alto, California, United States
in October, 2003 by Andy Rubin and others
Googleacquired Android Inc. in August 2005, making Android Inc. a
wholly owned subsidiary of Google Inc.
On November 5, 2007, the Open Handset Alliance, a consortium of
several companies which include Broadcom Corporation, Google, HTC,
Intel, LG, Marvell Technology Group, Motorola, Nvidia, Qualcomm,
Samsung Electronics, Sprint Nextel, T-Mobile and Texas Instruments
unveiled itself.
7. Licensing
With the exception of brief update periods, Android has been
available under a free software/open source license since October,
21 2008. Google published the entire source code (including network
and telephony stacks) under an Apache License.
Even though the software is open-source, device manufacturers
cannot use Google's Android trademark unless Google certifies that
the device complies with their Compatibility Definition Document
(CDD).
In early 2011, Google chose to temporarily withhold the source code
to the tablet-only Honeycomb release.
Honeycomb source code would not be released until after it was
merged with the Gingerbread release in Ice Cream Sandwich.
8. Code Access
Parts
Kernel
Android Open Source Project (AOSP)
Kernel
Should have access to latest shipped version => GPL
requirement
Google-maintained forks at android.git.kernel.org
AOSP
Usually Code-drops every 6 months
Official AOSP branches at android.git.kernel.org
9. Code Licenses
Kernel
GNU General Public License (a.k.a. GPL)
AOSP
Mostly Apache License 2.0 (a.k.a. ASL)
Having GPL-free user-space was a design goal
A few GPL and LGPL parts: mainly BlueZ and DBUS
Some key components in BSD: Bionic and Toolbox
external/ directory contains a mixed bag of licenses, incl. lots of
GPL
10. Versions
Ice Cream Sandwich
11. Version History
2008 - Sept.: Android 1.0 is released
2009 - Feb.: Android 1.1
2009 - Apr.: Android 1.5 / Cupcake
2009 - Sept.: Android 1.6 / Donut
2009 - Oct.: Android 2.0/2.1 / Eclair
2010 - May: Android 2.2 / Froyo
2010 - Dec.: Android 2.3 / Gingerbread
2011 - Jan : Android 3.0 / Honeycomb Tablet-optimized
2011 May: Android 3.1 USB host support
2011 Dec: Android 4.0 / Ice-Cream Sandwich merge Gingerbread and
Honeycomb
12. ANDROID BASICS
13. What is Android
Android is a software stack for mobile devices that includes an
operating system, middleware and key applications.
The Android SDK provides the tools and APIs necessary to begin
developing applications on the Android platform using the Java
programming language.
The Android NDK is a toolset that lets you embed components that
make use of native code (C/C++) in your Android applications.
14. Android Software Stack
15. Linux kernel
Android built on Linux 2.6 kernel
Provides security, memory management, process management, network
stack, and driver model
Abstraction layer between hardware and the software stack
16. Linux kernel Androidsm
17. Libraries
A set of C/C++ libraries exposed to developers through the
application framework
18. Libraries
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'sOpenCORE; 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
19. Libraries
Surface Manager - manages access to the display subsystem and
seamlessly composites 2D and 3D graphic layers from multiple
applications
FreeType - bitmap and vector font rendering
20. Libraries
LibWebCore - a modern web browser engine which powers both the
Android browser and an embeddable web view
SGL - the underlying 2D graphics engine
21. Libraries
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
SQLite - a powerful and lightweight relational database engine
available to all applications
22. Dalvik Virtual Machine
Runtime libraries provide most of the functionality in the core
Java libraries
Each app has a process and an instance of Dalvik VM
Uses Dalvik Executable (.dex) format low memory footprint
VM is register based runs compiled Java classes
The linux kernel provides Dalvik with needed functionality
23. Application Framework
The framework allows developers to build cool apps
24. Application Framework
Core System services
Activity manager (manages application lifecycle)
Package manager (loads apk files)
Window manager (handles applications window manager
interaction
with surface flinger)
Resource manager (handles media resources)
Content providers (provides data to application)
View system (provides widgets, views, layouts to
applications)
Hardware services
Provides low-level access to hardware device
Location manager
Telephony manager
Bluetooth service
WiFi service / USB service / Sensor service
25. Applications
AOSP and Non-AOSP Apps
26. Applications
The non-AOSP apps
Android Market
YouTube
Maps and Navigation
Gmail
Voice
SkyMap
...
Require
CTS/CDD Compliance
Signed agreement w/ Google
27. ANDROID APPLICATION FUNDAMENTALS
28. Application - User Interaction
29. Screen Characteristics
Screen size
Screen density
Orientation
Resolution
Density-independent pixel (dp)
30. Screen size & Density
Actual physical size, measured as the screen's diagonal.
The quantity of pixels within a physical area of the screen;
usually referred to as dpi (dots per inch). For example, a "low"
density screen has fewer pixels within a given physical area,
compared to a "normal" or "high" density screen.
31. Orientation
Landscape
Portrait
32. Resolution
The total number of physical pixels on a screen.
When adding support for multiple screens, applications do not work
directly with resolution; applications should be concerned only
with screen size and density, as specified by the generalized size
and density groups.
33. Density-independent pixel (dp)
A virtual pixel unit that you should use when defining UI layout,
to express layout dimensions or position in a density-independent
way.
The density-independent pixel is equivalent to one physical pixel
on a 160 dpi screen, which is the baseline density assumed by the
system for a "medium" density screen.
At runtime, the system transparently handles any scaling of the dp
units, as necessary, based on the actual density of the screen in
use.
The conversion of dp units to screen pixels is simple: px = dp *
(dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5
physical pixels.
You should always use dp units when defining your application's UI,
to ensure proper display of your UI on screens with different
densities.
34. Density Dependence
Example application without support for different densities, as
shown on low, medium, and high density screens.
Example application with good support for different densities (it's
density independent), as shown on low, medium, and high density
screens
35. Alternative drawables
36x36 for low-density
48x48 for medium-density
72x72 for high-density
96x96 for extra high-density
3:4:6:8 scaling ratio
res/drawable-mdpi/my_icon.png // bitmap for medium
densityres/drawable-hdpi/my_icon.png // bitmap for high
densityres/drawable-xhdpi/my_icon.png // bitmap for extra high
density
36. Screen Configuration
37. Screen Configuration
38. Application Fundamentals
Android applications are written in the Java programming
language.
The Android SDK tools compile the codealong with any data and
resource filesinto an Android package, an archive file with an .apk
suffix.
All the code in a single .apk file is considered to be one
application and is the file that Android-powered devices use to
install the application.
39. Security Sandbox
Once installed on a device, each Android application lives in its
own security sandbox:
The Android operating system is a multi-user Linux system in which
each application is a different user.
By default, the system assigns each application a unique Linux user
ID (the ID is used only by the system and is unknown to the
application). The system sets permissions for all the files in an
application so that only the user ID assigned to that application
can access them.
Each process has its own virtual machine (VM), so an application's
code runs in isolation from other applications.
By default, every application runs in its own Linux process.
Android starts the process when any of the application's components
need to be executed, then shuts down the process when it's no
longer needed or when the system must recover memory for other
applications.
40. Sharing Data
However, there are ways for an application to share data with other
applications and for an application to access system
services:
It's possible to arrange for two applications to share the same
Linux user ID, in which case they are able to access each other's
files. To conserve system resources, applications with the same
user ID can also arrange to run in the same Linux process and share
the same VM (the applications must also be signed with the same
certificate).
An application can request permission to access device data such as
the user's contacts, SMS messages, the mountable storage (SD card),
camera, Bluetooth, and more. All application permissions must be
granted by the user at install time.
41. What makes an Android Application
The core framework components that define your application.
The manifest file in which you declare components and required
device features for your application.
Resources that are separate from the application code and allow
your application to gracefully optimize its behavior for a variety
of device configurations.
42. Application Components
Application components are the essential building blocks of an
Android application.
Each component is a different point through which the system can
enter your application.
Not all components are actual entry points for the user
Each one exists as its own entity and plays a specific roleeach one
is a unique building block that helps define your application's
overall behavior.
43. Types of application components
Activities
Services
Content providers
Broadcast receivers
44. Activities
An activity represents a single screen with a user interface
Example of Activities in Email Application-
Email List
Compose
Read
Etc..
Although the activities work together to form a cohesive user
experience in the email application, each one is independent of the
others.
A different application can start any one of these activities (if
the email application allows it)
For example, a camera application can start the activity in the
email application that composes new mail, in order for the user to
share a picture.
45. Activities
46. Services
A service is a component that runs in the background to perform
long-running operations or to perform work for remote
processes.
A service does not provide a user interface.
For example, a service might play music in the background while the
user is in a different application
47. Services
48. Content Provider
A content provider manages a shared set of application data.
You can store the data in the file system, an SQLite database, on
the web, or any other persistent storage location your application
can access.
Through the content provider, other applications can query or even
modify the data (if the content provider allows it).
For example, the Android system provides a content provider that
manages the user's contact information. As such, any application
with the proper permissions can query part of the content provider
to read and write information about a particular person.
49. Broadcast Receiver
A broadcast receiver is a component that responds to system-wide
broadcast announcements.
Many broadcasts originate from the systemfor example, a broadcast
announcing that the screen has turned off, the battery is low, or a
picture was captured.
Applications can also initiate broadcasts
Although broadcast receivers don't display a user interface, they
may create a status bar notificationto alert the user when a
broadcast event occurs.
50. Androidism
Any application can start another applications component.
No main() function
Intent
51. Start Another Application
A unique aspect of the Android system design is that any
application can start another applications component.
For example, if you want the user to capture a photo with the
device camera, there's probably another application that does that
and your application can use it, instead of developing an activity
to capture a photo yourself.
You don't need to incorporate or even link to the code from the
camera application.
Instead, you can simply start the activity in the camera
application that captures a photo.
When complete, the photo is even returned to your application so
you can use it.
To the user, it seems as if the camera is actually a part of your
application.
52. Start Another Application
FACEBOOK APP
(PROCESS P1)
FACEBOOK APP
(PROCESS P1)
CAMERA APP
(PROCESS P2)
53. No MAIN()
When the system starts a component, it starts the process for that
application (if it's not already running) and instantiates the
classes needed for the component.
For example, if your application starts the activity in the camera
application that captures a photo, that activity runs in the
process that belongs to the camera application, not in your
application's process. Therefore, unlike applications on most other
systems, Android applications don't have a single entry point
(there's no main() function, for example).
54. No MAIN()
APP 2
(PROCESS P2)
APP 1
(PROCESS P1)
Camera Settings
Some Activity
Capture Photo
Save Photo
Use Photo
55. Intent
Because the system runs each application in a separate process with
file permissions that restrict access to other applications, your
application cannot directly activate a component from another
application.
56. Intent
Intent to Download
57. Activating Components
Three of the four component typesactivities, services, and
broadcast receiversare activated by an asynchronous message called
an intent.
Intents bind individual components to each other at runtime (you
can think of them as the messengers that request an action from
other components), whether the component belongs to your
application or another.
58. Activating Components
For activities and services, an intent defines the action to
perform (for example, to "view" or "send" something) and may
specify the URI of the data to act.
For example, an intent might convey a request for an activity to
show an image or to open a web page.
In some cases, you can start an activity to receive a result, in
which case, the activity also returns the result in an Intent
For broadcast receivers, the intent simply defines the announcement
being broadcast
59. Activating Components
Content provider, is not activated by intents.
It is activated when targeted by a request from a
ContentResolver.
The content resolver handles all direct transactions with the
content provider so that the component that's performing
transactions with the provider doesn't need to and instead calls
methods on the ContentResolver object.
This leaves a layer of abstraction between the content provider and
the component requesting information (for security).
60. Manifest File
Before the Android system can start an application component, the
system must know that the component exists by reading the
application's AndroidManifest.xml file (the "manifest" file).
Your application must declare all its components in this file,
which must be at the root of the application project
directory.
Activities, services, and content providers that you include in
your source but do not declare in the manifest are not visible to
the system and, consequently, can never run.
However, broadcast receivers can be either declared in the manifest
or created dynamically in code.
61. Manifest File
The manifest does a number of things in addition to declaring the
application's components, such as:
Identify any user permissions the application requires, such as
Internet access or read-access to the user's contacts.
Declare the minimum API Level required by the application, based on
which APIs the application uses.
Declare hardware and software features used or required by the
application, such as a camera, bluetooth services, or a multitouch
screen.
API libraries the application needs to be linked against (other
than the Android framework APIs), such as the Google Maps
library.
And more
62. Declaring components
63. Declaring components
You must declare all application components this way:
elements for activities
elements for services
elements for broadcast receivers
elements for content providers
64. Declaring component capabilities
You can use an Intent to start activities, services, and broadcast
receivers.
Can be done by explicitly naming the target component (using the
component class name) in the intent.
However, the real power of intents lies in the concept of intent
actions.
With intent actions, you simply describe the type of action you
want to perform (and optionally, the data upon which youd like to
perform the action) and allow the system to find a component on the
device that can perform the action and start it.
If there are multiple components that can perform the action
described by the intent, then the user selects which one to
use.
65. Declaring component capabilities
The way the system identifies the components that can respond to an
intent is by comparing the intent received to the intent
filtersprovided in the manifest file of other applications on the
device.
When you declare a component in your application's manifest, you
can optionally include intent filters that declare the capabilities
of the component so it can respond to intents from other
applications.
For example, an email application with an activity for composing a
new email might declare an intent filter in its manifest entry to
respond to "send" intents (in order to send email). An activity in
your application can then create an intent with the send action
(ACTION_SEND), which the system matches to the email applications
send activity and launches it when you invoke the intent with
startActivity().
66. Declaring application requirements
There are a variety of devices powered by Android and not all of
them provide the same features and capabilities.
In order to prevent your application from being installed on
devices that lack features needed by your application, it's
important that you clearly define a profile for the types of
devices your application supports by declaring device and software
requirements in your manifest file.
Most of these declarations are informational only and the system
does not read them, but external services such as Android Market do
read them in order to provide filtering for users when they search
for applications from their device.
67. Declaring application requirements
Important device characteristics
Screen size and density
Input configurations
Device features
Platform Version
68. Screen size and density
In order to categorize devices by their screen type, Android
defines two characteristics for each device:
screen size (the physical dimensions of the screen) and
screen density (the physical density of the pixels on the screen,
or dpidots per inch).
To simplify all the different types of screen configurations, the
Android system generalizes them into select groups that make them
easier to target. The screen sizes are: small, normal, large, and
extra large.
The screen densities are: low density, medium density, high
density, and extra high density.
By default, your application is compatible with all screen sizes
and densities, because the Android system makes the appropriate
adjustments to your UI layout and image resources.
However, you should create specialized layouts for certain screen
sizes and provide specialized images for certain densities, using
alternative layout resources, and by declaring in your manifest
exactly which screen sizes your application supports with the
element.
69. Input configurations
Many devices provide a different type of user input mechanism, such
as a hardware keyboard, a trackball, or a five-way navigation pad.
If your application requires a particular kind of input hardware,
then you should declare it in your manifest with the element.
70. Device features
There are many hardware and software features that may or may not
exist on a given Android-powered device, such as a camera, a light
sensor, bluetooth, a certain version of OpenGL, or the fidelity of
the touchscreen.
You should never assume that a certain feature is available on all
Android-powered devices (other than the availability of the
standard Android library), so you should declare any features used
by your application with the element.
71. Platform Version
Different Android-powered devices often run different versions of
the Android platform, such as Android 1.6 or Android 2.3.
Each successive version often includes additional APIs not
available in the previous version. In order to indicate which set
of APIs are available, each platform version specifies an API
Level
If you use any APIs that were added to the platform after version
1.0, you should declare the minimum API Level in which those APIs
were introduced using the element.
72. API Level
API Level is an integer value that uniquely identifies the
framework API revision offered by a version of the Android
platform.
The framework API consists of:
A core set of packages and classes
A set of XML elements and attributes for declaring a manifest
file
A set of XML elements and attributes for declaring and accessing
resources
A set of Intents
A set of permissions that applications can request, as well as
permission enforcements included in the system
73. API Level
Updates to the framework API are designed so that the new API
remains compatible with earlier versions of the API. That is, most
changes in the API are additive and introduce new or replacement
functionality.
The framework API that an Android platform delivers is specified
using an integer identifier called "API Level".
Each Android platform version supports exactly one API Level,
although support is implicit for all earlier API Levels (down to
API Level 1).
74. API Level
75. Application Resources
An Android application is composed of more than just codeit
requires resources that are separate from the source code, such as
images, audio files, and anything relating to the visual
presentation of the application.
you should define animations, menus, styles, colors, and the layout
of activity user interfaces with XML files.
Using application resources makes it easy to update various
characteristics of your application without modifying code andby
providing sets of alternative resourcesenables you to optimize your
application for a variety of device configurations (such as
different languages and screen sizes).
76. Application Resources
For every resource that you include in your Android project, the
SDK build tools define a unique integer ID, which you can use to
reference the resource from your application code or from other
resource
One of the most important aspects of providing resources separate
from your source code is the ability for you to provide alternative
resources for different device configurations. sources defined in
XML.
For example, by defining UI strings in XML, you can translate the
strings into other languages and save those strings in separate
files. Then, based on a language qualifier that you append to the
resource directory's name (such as res/values-fr/ for French string
values) and the user's language setting, the Android system applies
the appropriate language strings to your UI.
77. Application Resources
Same ID (R.ID)
but different Resource
78. DEVELOPING APPLICATIONS
79. Tools
Eclipse
Android Development Tools (ADT)
SDK
NDK
80. Steps
Set up Android Virtual Devices or hardware devices
Create an Android project
Build and run your application
Debug your application with the SDK debugging and logging
tools
Test your application with the Testing and Instrumentation
framework
81. Tutorial
Hello World
82. ACTIVITIES
83. Activity
An Activity is an application component that provides a screen with
which users can interact in order to do something
Each activity is given a window in which to draw its user
interface.
The window typically fills the screen, but may be smaller than the
screen and float on top of other windows.
84. Activity
An application usually consists of multiple activities that are
loosely bound to each other
Typically, one activity in an application is specified as the
"main" activity, which is presented to the user when launching the
application for the first time.
Each activity can then start another activity in order to perform
different actions.
85. Back Stack
Each time a new activity starts, the previous activity is stopped,
but the system preserves the activity in a stack (the "back
stack").
When a new activity starts, it is pushed onto the back stack and
takes user focus.
The back stack abides to the basic "last in, first out" queue
mechanism, so, when the user is done with the current activity and
presses the BACK key, it is popped from the stack (and destroyed)
and the previous activity resumes.
86. Back Stack
87. Back Stack
Two tasks: Task A is in the background, waiting to be resumed,
while Task B receives user interaction in the foreground
88. Back Stack
A single activity is instantiated multiple times
89. Creating Activity
Subclasss the Activity class
Implement User Interface
Declare Activity in the manifest
90. Sub class
To create an activity, you must create a subclass of Activity (or
an existing subclass of it).
In your subclass, you need to implement callback methods that the
system calls when the activity transitions between various states
of its lifecycle, such as when the activity is being created,
stopped, resumed, or destroyed.
91. Implement UI
The user interface for an activity is provided by a hierarchy of
viewsobjects derived from the View class.
Each view controls a particular rectangular space within the
activity's window and can respond to user interaction.
For example, a view might be a button that initiates an action when
the user touches it.
92. Implement UI
Android provides a number of ready-made views that you can use to
design and organize your layout.
"Widgets" are views that provide a visual (and interactive)
elements for the screen, such as a button, text field, checkbox, or
just an image.
"Layouts" are views derived from ViewGroup that provide a unique
layout model for its child views, such as a linear layout, a grid
layout, or relative layout.
You can also subclass the View and ViewGroup classes (or existing
subclasses) to create your own widgets and layouts and apply them
to your activity layout.
93. View & View Groups
Widget
Layout
94. Define UI
The most common way to define a layout using views is with an XML
layout file saved in your application resources.
This way, you can maintain the design of your user interface
separately from the source code that defines the activity's
behavior.
95. Define UI
96. Creating Activity Manifest
You must declare your activity in the manifest file in order for it
to be accessible to the system. To declare your activity, open your
manifest file and add an element as a child of the element.
... ... >
...
97. Creating Activity Manifest
There are several other attributes that you can include in this
element, to define properties such as the label for the activity,
an icon for the activity, or a theme to style the activity's
UI.
The android:name attribute is the only required attributeit
specifies the class name of the activity.
98. Intent Filters
An element can also specify various intent filtersusing the
elementin order to declare how other application components may
activate it.
When you create a new application using the Android SDK tools, the
stub activity that's created for you automatically includes an
intent filter that declares the activity responds to the "main"
action and should be placed in the "launcher" category. The intent
filter looks like this:
The element specifies that this is the "main" entry point to the
application. The element specifies that this activity should be
listed in the system's application launcher (to allow users to
launch this activity).
99. Intent Filters
If you intend for your application to be self-contained and not
allow other applications to activate its activities, then you don't
need any other intent filters. Only one activity should have the
"main" action and "launcher" category, as in the previous
example.
Activities that you don't want to make available to other
applications should have no intent filters and you can start them
yourself using explicit intents (as discussed in the following
section).
However, if you want your activity to respond to implicit intents
that are delivered from other applications (and your own), then you
must define additional intent filters for your activity.
For each type of intent to which you want to respond, you must
include an that includes an element and, optionally, a element
and/or a element. These elements specify the type of intent to
which your activity can respond.
100. Lab
Hello World Tutorial
101. Starting an Activity
You can start another activity by calling startActivity(), passing
it an Intent that describes the activity you want to start. The
intent specifies either-
the exact activity you want to start or
describes the type of action you want to perform (and the system
selects the appropriate activity for you, which can even be from a
different application).
An intent can also carrysmall amounts of data to be used by the
activity that is started.
102. Starting an Activity
When working within your own application, you'll often need to
simply launch a known activity. You can do so by creating an intent
that explicitly defines the activity you want to start, using the
class name.
For example, here's how one activity starts another activity named
SignInActivity:
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
103. Lab
Create a new activity
Start a new activity from the Main activity
104. Starting an Activity
your application might also want to perform some action, such as
send an email, text message, or status update, using data from your
activity
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
startActivity(intent);
105. Lab
Create a new activity
Start the new activity from Main activity
Pass data to new activity
106. Starting an activity for a result
Sometimes, you might want to receive a result from the activity
that you start.
In that case, start the activity by calling
startActivityForResult() (instead of startActivity()).
To then receive the result from the subsequent activity, implement
the onActivityResult() callback method.
When the subsequent activity is done, it returns a result in an
Intent to your onActivityResult() method.
107. Shutting Down an Activity
You can shut down an activity by calling its finish() method. You
can also shut down a separate activity that you previously started
by calling finishActivity().
Note: In most cases, you should not explicitly finish an activity
using these methods. As discussed in the following section about
the activity lifecycle, the Android system manages the life of an
activity for you, so you do not need to finish your own activities.
Calling these methods could adversely affect the expected user
experience and should only be used when you absolutely do not want
the user to return to this instance of the activity.
108. Lab
Create a new activity
Start the new activity for result from Main activity
Get result from new activity
109. Managing the Activity Lifecycle
An activity can exist in essentially three states:
Resumed The activity is in the foreground of the screen and has
user focus. (This state is also sometimes referred to as
"running".)
Paused Another activity is in the foreground and has focus, but
this one is still visible. That is, another activity is visible on
top of this one and that activity is partially transparent or
doesn't cover the entire screen. A paused activity is completely
alive (the Activity object is retained in memory, it maintains all
state and member information, and remains attached to the window
manager), but can be killed by the system in extremely low memory
situations.
Stopped The activity is completely obscured by another activity
(the activity is now in the "background"). A stopped activity is
also still alive (the Activity object is retained in memory, it
maintains all state and member information, but is not attached to
the window manager). However, it is no longer visible to the user
and it can be killed by the system when memory is needed
elsewhere.
110. Implementing the lifecycle callbacks
When an activity transitions into and out of the different states
described above, it is notified through various callback methods.
All of the callback methods are hooks that you can override to do
appropriate work when the state of your activity changes.
111. Implementing the lifecycle callbacks
112. Activity Lifecycle
113. Saving persistent Data
The activity is killable after-
onPause()
onStop()
onDestroyed()
onPause() is the last method that's guaranteed to be called before
the process can be killedif the system must recover memory in an
emergency, then onStop() and onDestroy() might not be called.
Therefore, you should use onPause() to write crucial persistent
data (such as user edits) to storage.
However, you should be selective about what information must be
retained during onPause(), because any blocking procedures in this
method block the transition to the next activity and slow the user
experience.
114. Lab
Saving Activity Data
LunarLander
115. Saving activity state
when an activity is paused or stopped, the state of the activity is
retained. This is true because the Activity object is still held in
memory when it is paused or stoppedall information about its
members and current state is still alive. Thus, any changes the
user made within the activity are retained in memory, so that when
the activity returns to the foreground (when it "resumes"), those
changes are still there.
However, when the system destroys an activity in order to recover
memory, the Activity object is destroyed, so the system cannot
simply resume it with its state intact. Instead, the system must
recreate the Activity object if the user navigates back to it. Yet,
the user is unaware that the system destroyed the activity and
recreated it and, thus, probably expects the activity to be exactly
as it was.
116. Saving activity state
117. Saving activity state
The callback method in which you can save information about the
current state of your activity is onSaveInstanceState().
The system calls this method before making the activity vulnerable
to being destroyed and passes it a Bundle object.
The Bundle is where you can store state information about the
activity as name-value pairs, using methods such as
putString().
Then, if the system kills your activity's process and the user
navigates back to your activity, the system passes the Bundle to
onCreate() so you can restore the activity state you saved during
onSaveInstanceState().
If there is no state information to restore, then the Bundle passed
to onCreate() is null.
118. Saving activity state
Even if you do nothing and do not implement onSaveInstanceState(),
some of the activity state is restored by the Activity class's
default implementation of onSaveInstanceState().
Specifically, the default implementation calls
onSaveInstanceState() for every View in the layout, which allows
each view to provide information about itself that should be
saved.
Almost every widget in the Android framework implements this method
as appropriate, such that any visible changes to the UI are
automatically saved and restored when your activity is
recreated.
For example, the EditText widget saves any text entered by the user
and the CheckBox widget saves whether it's checked or not. The only
work required by you is to provide a unique ID (with the android:id
attribute) for each widget you want to save its state.
If a widget does not have an ID, then it cannot save its
state.
119. Handling configuration changes
Some device configurations can change during runtime (such as
screen orientation, keyboard availability, and language).
When such a change occurs, Android restarts the running Activity
(onDestroy() is called, followed immediately by onCreate()).
The restart behavior is designed to help your application adapt to
new configurations by automatically reloading your application with
alternative resources that you've provided.
The best way to handle a configuration change, such as a change in
the screen orientation, is to simply preserve the state of your
application using onSaveInstanceState() and
onRestoreInstanceState() (or onCreate())
120. Lab
Saving Activity State
Default onSaveInstanceState() Behavior
121. Handling Runtime Changes
Some device configurations can change during runtime (such as
screen orientation, keyboard availability, and language). When such
a change occurs, Android restarts the running Activity (onDestroy()
is called, followed by onCreate()).
The restart behavior is designed to help your application adapt to
new configurations by automatically reloading your application with
alternative resources.
Your application should be able to restart at any time without loss
of user data or state
122. Handling Runtime Changes
If restarting your Activity requires that you recover large sets of
data, re-establish a network connection, or perform other intensive
operations, then a full restart due to a configuration change might
be an unpleasant user experience.
Also, it may not be possible for you to completely maintain your
Activity state with the Bundle that the system saves for you during
the Activity lifecycleit is not designed to carry large objects
(such as bitmaps) and the data within it must be serialized then
deserialized, which can consume a lot of memory and make the
configuration change slow.
In such a situation, you can alleviate the burden of reinitializing
your Activity by retaining a stateful Object when your Activity is
restarted due to a configuration change.
123. Handling Runtime Changes
To retain an Object during a runtime configuration change:
Override the onRetainNonConfigurationInstance() method to return
the Object you would like to retain.
Android calls onRetainNonConfigurationInstance() between onStop()
and onDestroy() when it shuts down your Activity due to a
configuration change.
When your Activity is created again, call
getLastNonConfigurationInstance() to recover your Object.
124. Handling Runtime Changes
125. Activity Summary
Activity Lifecycle
Save persistent data
Save persistent state
Handle runtime configuration changes
126. USER INTERFACE
127. User Interface
In an Android application, the user interface is built using View
and ViewGroup objects. There are many types of views and view
groups, each of which is a descendant of the View class.
View objects are the basic units of user interface expression on
the Android platform.
The View class serves as the base for subclasses called "widgets,"
which offer fully implemented UI objects, like text fields and
buttons.
The ViewGroup class serves as the base for subclasses called
"layouts," which offer different kinds of layout architecture, like
linear, tabular and relative.
128. User Interface
A View object is a data structure whose properties store the layout
parameters and content for a specific rectangular area of the
screen.
A View object handles its own measurement, layout, drawing, focus
change, scrolling, and key/gesture interactions for the rectangular
area of the screen in which it resides.
As an object in the user interface, a View is also a point of
interaction for the user and the receiver of the interaction
events.
129. View & View Groups
Widget
Layout
130. View Hierarchy
131. View Hierarchy
In order to attach the view hierarchy tree to the screen for
rendering, your Activity must call the setContentView() method and
pass a reference to the root node object. The Android system
receives this reference and uses it to invalidate, measure, and
draw the tree. The root node of the hierarchy requests that its
child nodes draw themselves in turn, each view group node is
responsible for calling upon each of its own child views to draw
themselves.
Android parses the elements of your layout in-order (from the top
of the hierarchy tree), instantiating the Views and adding them to
their parent(s). Because these are drawn in-order, if there are
elements that overlap positions, the last one to be drawn will lie
on top of others previously drawn to that space.
132. Layout
Your layout is the architecture for the user interface in an
Activity.
It defines the layout structure and holds all the elements that
appear to the user.
You can declare your layout in two ways:
Declare UI elements in XML. Android provides a straightforward XML
vocabulary that corresponds to the View classes and subclasses,
such as those for widgets and layouts.
Instantiate layout elements at runtime. Your application can create
View and ViewGroup objects (and manipulate their properties)
programmatically.
133. Layout
The advantage to declaring your UI in XML is that it enables you to
better separate the presentation of your application from the code
that controls its behavior. Your UI descriptions are external to
your application code, which means that you can modify or adapt it
without having to modify your source code and recompile. For
example, you can create XML layouts for different screen
orientations, different device screen sizes, and different
languages.
Additionally, declaring the layout in XML makes it easier to
visualize the structure of your UI, so it's easier to debug
problems. As such, this document focuses on teaching you how to
declare your layout in XML.
134. Declaring Layout
The most common way to define your layout and express the view
hierarchy is with an XML layout file.
Each element in XML is either a View or ViewGroup object (or
descendant thereof). View objects are leaves in the tree, ViewGroup
objects are branches in the tree
135. Declaring Layout
136. Declaring Layout
The name of an XML element is respective to the Java class that it
represents. So a element creates a TextView in your UI, and a
element creates a LinearLayout view group.
When you load a layout resource, the Android system initializes
these run-time objects, corresponding to the elements in your
layout.
137. Declaring Layout
Each layout file must contain exactly one root element, which must
be a View or ViewGroup object. Once you've defined the root
element, you can add additional layout objects or widgets as child
elements to gradually build a View hierarchy that defines your
layout.
After you've declared your layout in XML, save the file with the
.xml extension, in your Android project's res/layout/ directory, so
it will properly compile.
138. Loading Layout
When you compile your application, each XML layout file is compiled
into a View resource.
You should load the layout resource from your application code, in
your Activity.onCreate() callback implementation.
Do so by calling setContentView(), passing it the reference to your
layout resource in the form of: R.layout.layout_file_name
For example, if your XML layout is saved as main_layout.xml, you
would load it for your Activity like so:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
139. XML Attributes
Every View and ViewGroup object supports their own variety of XML
attributes.
Some attributes are specific to a View object (for example,
TextView supports the textSize attribute)
Some are common to all View objects, because they are inherited
from the root View class (like the id attribute).
And, other attributes are considered "layout parameters," which are
attributes that describe certain layout orientations of the View
object, as defined by that object's parent ViewGroup object.
140. ID
Any View object may have an integer ID associated with it, to
uniquely identify the View within the tree.
When the application is compiled, this ID is referenced as an
integer, but the ID is typically assigned in the layout XML file as
a string, in the id attribute.
This is an XML attribute common to all View objects (defined by the
View class) and you will use it very often.
The syntax for an ID, inside an XML tag is:
android:id="@+id/my_button"
The at-symbol (@) at the beginning of the string indicates that the
XML parser should parse and expand the rest of the ID string and
identify it as an ID resource.
The plus-symbol (+) means that this is a new resource name that
must be created and added to our resources (in the R.java
file).
141. Android Framework ID
There are a number of other ID resources that are offered by the
Android framework.
When referencing an Android resource ID, you do not need the
plus-symbol, but must add the android package namespace, like
so:
android:id="@android:id/empty"
With the android package namespace in place, we're now referencing
an ID from the android.R resources class, rather than the local
resources class.
142. Defining & Accessing Views
In order to create views and reference them from the application, a
common pattern is to:
Define a view/widget in the layout file and assign it a unique
ID:
Then create an instance of the view object and capture it from the
layout (typically in the onCreate() method):
Button myButton = (Button) findViewById(R.id.my_button);
143. Layout Parameters
Visualization of a view hierarchy with layout parameters associated
with each view.
144. Layout Parameters
XML layout attributes named layout_something define layout
parameters for the View that are appropriate for the ViewGroup in
which it resides.
every LayoutParams subclass has its own syntax for setting values.
Each child element must define LayoutParams that are appropriate
for its parent, though it may also define different LayoutParams
for its own children.
All view groups include a width and height (layout_width and
layout_height), and each view is required to define them.
Many LayoutParams also include optional margins and borders.
145. Layout Parameters
You can specify width and height with exact measurements, though
you probably won't want to do this often. More often, you will use
one of these constants to set the width or height:
wrap_content tells your view to size itself to the dimensions
required by its content
fill_parent tells your view to become as big as its parent view
group will allow.
In general, specifying a layout width and height using absolute
units such as pixels is not recommended. Instead, using relative
measurements such as density-independent pixel units (dp),
wrap_content, or fill_parent, is a better approach, because it
helps ensure that your application will display properly across a
variety of device screen sizes.
146. Layout Position
The geometry of a view is that of a rectangle. A view has a
location, expressed as a pair of left and top coordinates, and two
dimensions, expressed as a width and a height. The unit for
location and dimensions is the pixel.
It is possible to retrieve the location of a view by invoking the
methods getLeft() and getTop(). The former returns the left, or X,
coordinate of the rectangle representing the view. The latter
returns the top, or Y, coordinate of the rectangle representing the
view. These methods both return the location of the view relative
to its parent. For instance, when getLeft() returns 20, that means
the view is located 20 pixels to the right of the left edge of its
direct parent.
In addition, several convenience methods are offered to avoid
unnecessary computations, namely getRight() and getBottom(). These
methods return the coordinates of the right and bottom edges of the
rectangle representing the view. For instance, calling getRight()
is similar to the following computation: getLeft() +
getWidth().
147. Layout Position
getTop()
getBottom()
getLeft()
View
getRight()
Parent
148. Size, Padding and Margins
149. Size, Padding and Margins
The size of a view is expressed with a width and a height. A view
actually possess pairs of width and height values.
The pair is simply known as width and height, or sometimes drawing
width and drawing height. These dimensions define the actual size
of the view on screen, at drawing time and after layout. The width
and height can be obtained by calling getWidth() and
getHeight().
To measure its dimensions, a view takes into account its padding.
The padding is expressed in pixels for the left, top, right and
bottom parts of the view. Padding can be used to offset the content
of the view by a specific amount of pixels. For instance, a left
padding of 2 will push the view's content by 2 pixels to the right
of the left edge. Padding can be set using the setPadding(int, int,
int, int) method and queried by calling getPaddingLeft(),
getPaddingTop(), getPaddingRight() and getPaddingBottom().
150. Common layout Objects
151. Common layout Objects
152. Linear layout
153. Table Layout
154. Relative Layout
155. Lab
XML & Layout Window
Layouts
Linear
Relative
Table
Grid
Tab
List
156. Widgets
A widget is a View object that serves as an interface for
interaction with the user. Android provides a set of fully
implemented widgets, like buttons, checkboxes, and text-entry
fields, so you can quickly build your UI.
Some widgets provided by Android are more complex, like a date
picker, a clock, and zoom controls. But you're not limited to the
kinds of widgets provided by the Android platform.
If you'd like to do something more customized and create your own
actionable elements, you can, by defining your own View object or
by extending and combining existing widgets.
157. Widgets
158. Lab
Widgets
- Date Picker
159. Time Picker 160. Form Stuff 161. Spinner 162. Auto Complete 163. Gallery 164. Web View