View
560
Download
2
Category
Preview:
Citation preview
UNIT 1Android Basics
1
CHAPTER 1Introduction to Android
The term “Android” has its origin in the Greek word andr-, meaning “man or male” and the suffix
eides, used to mean “alike or of the species”. This together means as much as “being human”. Android
is a software platform and operating system for mobile devices, based on the Linux operating system
and developed by Google and later the Open Handset Alliance. It allows developers to write managed
code in a Java-like language that utilizes Google-developed Java libraries, but does not support
programs developed in native code. Android is just an OS, it requires hardware to run on. Android is
hailed as “the first complete, open, and free mobile platform”. Android offers a full stack: an
operating system, middleware, and key mobile applications. It also contains a rich set of APIs that
allows third-party developers to develop great applications. Google released most of the Android code
under the Apache License, a free software and open source license.
Android does not differentiate between the phone's core applications and third-party applications.
They can all be built to have equal access to a phone's capabilities providing users with a broad
spectrum of applications and services. With devices built on the Android Platform, users are able to
fully tailor the phone to their interests. Android breaks down the barriers to building new and
innovative applications. Android provides access to a wide range of useful libraries and tools that can
be used to build rich applications. In addition, Android includes a full set of tools that have been built
from the ground up alongside the platform providing developers with high productivity and deep
insight into their applications.
Why is Google Launching Android?
Almost everyone recognises that mobile is the next big advertising medium. Google is behind some of its
rivals in mobile (for instance in mobile search where Yahoo and mobile specialist like Medio Systems and
JumpTap lead the way), so this is its way of “catching up”. They want a piece of the mobile advertising
2
market. Google CEO Eric Schmidt was quoted as saying that “he's less than impressed with the advertising
possibilities for properties like YouTube, and Web 2.0 in general. But mobile, well, that's a different thing.”
Rather than building the hardware (like Apple), Google have stuck to what they are good at and built the
software. In the long run they will look into where and how they can insert ads into Android.
The key advantage that an operating system (OS) like Android has (over the iPhone OS) is that its open
systems and standards will allow 3rd parties to develop apps with no interference or limits. Clearly Google
believe that the success of Android will be made by the quality of the apps that it has available.
At the press conference to announce the release of the T-mobile G-1, Cole Brodman, Chief Technology and
Innovation officer for T-Mobile said: “The open market place is really going to drive innovation on this
platform” Advocates of Apple’s approach say that customers are protected from bad user experiences by Apple
controlling which apps to approve and which to deny. The same argument was used by the mobile carriers
about their ‘walled garden’ approach, and has not proven successful. People don’t want to be told what they
can and can’t do, not just when it comes to watching porn (which the iPhone apps don’t allow) but about
everything.
1.1 History of Android
The first worldwide mobile network was introduced by the USA in 1946 and could only
be used nationally at this time, mostly for military purposes. Not until the end of the 1950’s was
this technique replaced by the Analog network (A-network). Then, in 1973, Motorola presented a
prototype of the world’s first cellular telephone. It was about one foot long, weight almost 2
pounds and cost $3995. This cell phone which became commercially available in 1983 provided
one hour of talk time and could store 30 phone numbers. In only one year 300.000 people,
worldwide, were owners, considering price, this was remarkable market growth.
3
Figure 1.1: Historical development of cell phones
In 1982 the Finnish handset maker Nokia introduced its first Mobile phone, “Mobira
Senator”. This device looked very much like a portable radio and weight 21 pounds. The first
cell phone with PDA features was introduced in 1993 by Bell South/IBM. It included phone and
pager functionalities, calculator and calendar applications as well as fax and e-mail capability.
The weight was about 18 pounds and it sold for $900. Motorola’s “StarTac”, in 1996, merged
fashion and functionality. Its weight was about 3.1 pound’s which is lighter than some of today’s
cell phones. Kyocera introduces its QCP6035 mobile phone in year 2000. It was the first widely
available Palm OS based phone.
In 2002 the Danger Hip top, later known as the T-Mobile Sidekick, was introduced. It was
one of the first mobile devices to include a Web browser, reliable e-mail access and instant
messaging. With the RAZRv3 Motorola again came back and started a trend towards ultra-thin,
stylish phones. It was the first mobile device which many people from high scholars to
businessmen wanted to have, primarily, because of its style and because it was fashionably. It is
still one of the most popular mobile phones today. The last very impressing innovation was
presented by Apple with the release of the iPhone in 2007, a beautifully designed cell phone that
includes an innovative touch screen navigation interface.
4
S.no. Year Description
1 2005
Google acquired Android, Inc., a small company that developed
software for mobile phones. In the following months, the former
“Android, Inc.” team started working on a Linux-based OS for
mobile devices.
2 2006Media and press was filled with news about Google entering the
mobile market.
3 2007In November 2007, the Open Handset Alliance was announced.
OHA’s first project was Android.
Table 1.1: History of Android
In a nutshell changes of the hardware related mostly to improvements in weight, price and
look. The operating system was improved by e.g. games, calendar applications, email
applications and other functionalities to use the internet. This development underlines clearly
what a cell phone needs today. It must be as small as possible, it has to be “stylish” and it has to
cover a wide range of functions especially internet connection which is used by many people in
the world every day. Android had emerged as one such operating system which provide most of
such demanded features.
1.2 Architecture of the Android Platform
The Android platform is designed to be more fault-tolerant than many of its predecessors. The
handset runs a Linux operating system, upon which Android applications are executed in a
secure fashion. Each Android application runs in its own virtual machine. Android applications
are managed code; therefore, they are much less likely to cause the phone to crash, leading to
fewer instances of device corruption.
5
Figure1.2: Major components of the Android operating system
Major components of the Android operating system are:
1. The application layer:
These are all the applications hosted on the handset. Google or any other 3rd party may have
written these applications. Unlike other phone platforms, Android has support for applications
that do not have a user interface. The main application types are:
a) User interface applications. Consisting of views that know how to draw themselves on
screen.
b) Intent listeners. Intents are messages that are carried over the message bus of the handset.
This allows for different applications on the phone to talk to each other.
6
c) Services. Similar to Windows services or UNIX daemon processes. A body of code that
runs in the background. The application runs without a user interface but may be essential
to an application that does have a user interface.
d) Content providers: a data storehouse that provides access to data on the device.
On Android, unlike all other mobile platforms, all data and files that are created by an
application are invisible to all other installed applications. In order to make data visible to other
applications, the application or service must make the data available via content providers.
Alternatively, an application may only interact with a content provider for its data needs and
forego the creation of data and files completely. Unlike other platforms, Android already has a
generic, standard way of accessing data in a uniform and standard fashion.The Android software
platform will come with a set of basic applications like browser, email client, SMS program,
maps, calendar, contacts and many more. All these applications are written using the Java
programming language. It should be mentioned that applications can be run simultaneously; it is
possible to hear music and read an email at the same time. This layer will mostly be used by
commonly cell phone users.
2. The application framework:
In this layer, the application developer has access to what Android refers to as “service”
processes. These services are invisible to the user of the handset. Application developers can
communicate with these services via a message bus. For example, a contact application
might instigate a phone call at the behest of a user request by calling on the services of the
telephony manager. All code found in this section is currently closed source, is written in Java
specifically for the Dalvik virtual machine. It is not yet clear under what license these modules
will be made available in the future. An application framework is a software framework that is
used to implement a standard structure of an application for a specific operating system. With the
help of managers, content providers and other services programmers it can reassemble functions
used by other existing applications.
7
3. The libraries
The green layer consists entirely of open source libraries available under various licenses.
Some of the libraries come from the GNU project8 itself. The licenses here vary from the LGPL,
BSD, MIT and are completely in the public domain11 in the case of the SQLite12 database.
However, even if the licenses of some of the components found in this layer are more
permissive and could allow a hardware vendor for customizations not found in other Android
handsets, Google has created the Open Handset Alliance13 that owns the Android trademark.
As part of this effort, any phone that wishes to be branded as an Android handset must meet
the non-fragmentation rule14. As such, any phone that would customize the libraries found in
this layer, add libraries or remove them altogether would no longer be able to brand itself as
an Android phone. Furthermore, under this same pledge, its license to the proprietary Dalvik
virtual machine found at the core of the Android platform would be considered null and void.
The available libraries are all written in C/C++. They will be called through a Java interface.
These includes the Surface Manager (for compositing windows), 2D and 3D graphics, Media
Codecs like MPEG-4 and MP3, the SQL database SQLite and the web browser engine Web Kit.
Notable software included in this layer, but not limited to, are:
a) Webkit: The Web browser engine found at the heart of the Apple Safari, iPhone and
Konqueror web browsers. Providing an Acid2 compliant web browser featuring HTML,
JavaScript and CSS. This browser is now also used on high end Nokia phones.
b) SQLite: This database is the de facto database for embedded products and is now most
likely the most widely used database in the world21. It is incredibly small; the library fits
comfortably in less than 500KB on disk and yet offers most features found in the SQL-92
standard.
c) OpenSSL: The SSL/TLS24 security library used in all Mozilla25 based products, Apple
Mac OS X, Linux and many commercial UNIX operating systems.
d) OpenGL ES: OpenGL is a 3D graphics library used by many games, operating systems
and applications to achieve high performance 3D graphics. Android’s use of such a
8
library allows application providers to tap into a well-known pool of experts on this
technology. OpenGL ES is the embedded version of the OpenGL library and features a
subset of the OpenGL API. Additional functionality specific to low powered
environments such as phones is also provided by the ES variant of OpenGL.
4. The runtime:
Found in the green layer of the Android application stack are the Dalvik virtual machine
and the core Java libraries that are used to run and create applications respectively.
Available Java API Packages
The core Java packages that are used to create applications come from two different sources:
a) Google Android specific packages: These packages were created by Google for its Android
initiative. They are currently closed source, but Google has committed to making these packages
Open Source30. The packages range from user interface construction to hardware specific
functions such as camera control, Bluetooth support, and location services.
b) Java packages that are part of the Java SE 5 specification, these packages represent the bulk
of the Android SDK. In other words, regular Java SE 5 developers can leverage their existing
skills to write Android applications. Google obtained these packages from the Apache Harmony
project. As such, these packages are licensed under the Apache Software Foundation License
version 2. This license is one of the most liberal available today. Companies can use, modify,
and commercially exploit code under this license without the need to re-contribute changes back
to the original source or any 3 rd parties. However, the Android pledge from the Open Handset
Alliance still applies at this layer of the software stack meaning that any changes here will
disallow the use of the Android brand and Dalvik virtual machine. That being said, not all
existing Java SE 5 knowledge applies. The user interface toolkits from Java SE i.e., Swing and
AWT, have been stripped in favor of an Android only specific toolkit.
The Dalvik Virtual Machine
9
The Dalvik virtual machine is an interpreter only machine optimized for use on low
powered, low memory devices like phones. Notably, Dalvik does not make use of just in time
(JIT) compilation to improve the performance of an application at runtime. Furthermore, Dalvik
is not a Java virtual machine. This is because Dalvik is unable to read Java bytecode34, instead it
uses its own bytecode format called “dex”. Google claims this format allows battery power to be
better conserved at all different stages of execution of an application. This means that standard
Java SE applications and libraries cannot be used directly on the Android Dalvik virtual
machine.
Dalvik however stands at the center of the Android value proposition. Its low electrical power
consumption, rich libraries, and unified, non-fragmented application programming interfaces
make it stand out, or so Google hopes, over the fragmented ecosystem that is Java ME35 today.
Furthermore, since Dalvik uses the Java programming language but not the Java execution
environment (JVM), Google is free to develop Android without the need to license or obtain
certification from Sun Microsystems Inc, the legal owner of the Java trademark and brands. The
Android runtime consists of two components. First is a set of core libraries which provides most
of the functionality available in the core libraries of the Java programming language. Second the
virtual machine Dalvik which operates like a translator between the application side and the
operating system. Every application which runs on Android is written in Java. As the operating
system is not able to understand this programming language directly, the Java programs will be
received and translated by the virtual machine Dalvik. The translated code can then be executed
by the operating system. A very important thing to notice is that applications will be
encapsulated in Dalvik. For every program an own virtual machine is available even if some
programs are running parallel. The advantage is that the different programs do not affect each
other, so a program error for example can lead to a crash of the program but not of the whole
system.
5. The kernel
10
The red layer from figure 1 represents the services offered by the Linux kernel and
associated GNU utility packages ported to the ARM4 architecture. These components are
licensed under the GNU General Public License, the GPL5, or the GNU Lesser General Public
License, the LGPL. Being subject to the GNU GPL and LGPL licenses, these components are
licensed with all source code included. Furthermore, due to the viral nature of the GPL license,
any modification to this layer or derived work must be distributed as source to any 3rd parties
using the same licensing terms. The GNU/Linux ARM port is mature, stable, and used in
many embedded projects both in and outside of Google. The Linux Kernel will be used by
Android for its device drivers, memory management, process management and networking.
Android is built on the Linux kernel, but Android is not Linux as it has no native windowing
system, no glibc support and does not include the full set of standard Linux utilities.
Fig 1.3: Flow diagram
Problems in Binder
Applications and services may run in separate processes but must communicate and share data.
11
Inter Process Communication (IPC) can introduce significant processing overhead and security
holes.
Solution to the problem can be having driver to facilitate inter-process communication (IPC).
High performance can be achieved through shared memory. Per-process thread pool for
processing requests, reference counting, and mapping of object references
across processes and Synchronous calls between processes are some possible solutions.
Fig 1.4: Power Management
Power management problem with solution:
Mobile devices run on battery power but batteries have limited capacity. Thus managing the
power of the mobile device is an important issue.
Built on top of standard Linux Power Management (PM) has more aggressive power
management policy. Components make requests to keep the power on through
12
“wake locks”.
1.3 Android Physiology
Similar to most Linux-based systems at startup, the bootloader loads the Linux kernel and starts
the init process.
Init starts Linux daemons, including:
a) USB Daemon (usbd) to manage USB connections
b) Android Debug Bridge (adbd) to manage ADB connections
c) Debugger Daemon (debuggerd) to manage debug processes requests (dump memory,
etc.)
d) Radio Interface Layer Daemon (rild) to manage communication with the radio
Fig 1.4 Android Physiology
13
Init process starts the zygote process:
a) A nascent process which initializes a Dalvik VM instance
b) Loads classes and listens on socket for requests to spawn VMs
c) Forks on request to create VM instances for managed processes
d) Copy-on-write to maximize re-use and minimize footprint Init starts runtime process:
e) Initializes Service Manager – the context manager for Binder that handles service registration
and lookup
f) Registers Service Manager as default context manager for Binder services Runtime process
sends request for Zygote to start System Service Runtime process sends request for Zygote to
start System Server
g) Zygote forks a new VM instance for the System Service process and starts the service
System Service starts the native system servers, including:
a) Surface Flinger
b) Audio Flinger
Native system servers register with Service Manager as IPC service targets. System Service
starts the Android managed services.
Layer Interaction
There are 3 main flavors of Android layer cake:
• App → Runtime Service → lib
• App → Runtime Service → Native Service → lib
• App → Runtime Service → Native Daemon → lib
14
CHAPTER 2Features of Android Platform
Some of the features of Android platform are as follows:
1. Complete: The designers took a comprehensive approach when they developed the Android
platform. They began with a secure operating system and built a robust software framework
that allows for rich application development opportunities.
2. Open: The Android platform is provided through open source licensing. Developers have
unprecedented access to the handset features when developing applications.
3. Free: Android applications are free to develop. There are no licensing or royalty fees to
develop on the platform. Membership fee is not required. No requirement of testing fees.
Signing or certification fees are also not required.
There are many improvements and additional features introduced in Android as compared to
previous mobile operating systems. These can be enlisted as follows:
1. Reusability-Application framework enabling reuse and replacement of components.
2. Optimization-Dalvik virtual machine optimized for mobile devices.
3. Open Source-Integrated browser based on the open source web kit engine.
4. Optimized graphics-Optimized graphics powered by a custom 2D graphics library; 3D
graphics based on the OpenGL ES 1.0 specification which is hardware acceleration optional.
5. Structured Data Storage-SQLite for structured data storage
6. Media support-Media support for common audio, video, and still image formats (MPEG4,
H.264, MP3, AAC, AMR, JPG, PNG, GIF) GSM Telephony (hardware dependent).
7. Environment-Rich development environment including a device emulator, tools for
debugging, memory and performance profiling, and a plug-in for the Eclipse IDE.
15
8. Portability-Portability is a very important assessment criterion. The Android Mobile
platform is a Linux based system and has the big advantage that this operating system can be
used on many different platforms. The open access will help to collect a lot of experience
which will make it easier in the future to access other sections. The fact that Android is based
on the standardized programming language Java, which is also used for application
development, underlines the importance of portability for this platform.
9. Reliability-The Linux kernel, used by Android, has existed for more than a decade and has
proven that it is stable and fail-proof. Therefore it is useful for mobile applications. Now
days it is often used on Web Servers or similar applications which require a high degree of
reliability. So Android will not rank behind any existing operating system in reliability.
10. Connectivity-As far as connectivity is concerned Android features GSM telephony,
Bluetooth, EDGE which is a technique to increase the data rate in GSM mobile network , 3D
i.e. third generation mobile standards, and WI-FI. All developers have the same access to the
framework APIs used by the core applications.
11. Product Diversity-The most important feature concerning product diversity is to make the
relevant product open to the market for development which guarantees product diversity and
this feature is provided by Android operating system.
12. Open Platform-Android was built from the ground up with the explicit goal to be the first
open, complete, and free platform created specifically for mobile devices. An “open mobile
platform” is a software stack, including an operating system, middleware and key
applications, which can be used on every mobile device. It allows users to develop additional
software and change or replace functionality without limitations. The most common
standards for communication and connectivity are used. All these functionalities have to be
free of charge.
13. Standardization-Android is based on the standardized programming language Java. This is
also the only programming language used to develop applications. The advantage of Java is
that its programs can run on any platform without having to be rewritten. This is also a
positive aspect of portability.
16
14. Multiprocessing-Android is a multiprocessing system, where each application runs as its
own process. Most security between applications and the system is enforced at the process
level through standard Linux facilities, such as user and group IDs that are assigned to
application.
17
CHAPTER 3Present and Future aspects of Android Platform
With Android being part of the Open Handset Alliance, the other members of the alliance
will follow T-Mobile’s lead and unveil their products for Android. For instance Qualcomm have
announced that it is working on more than five Android based handsets to be released during Q1
2009. Android being free also means that smaller handset manufacturers don’t have to worry
about the (very large) headache of writing and maintaining an operating system.
3.1 Company Tie Ups
The founding members of the Open Handset Alliance are:
S.No. Company type Company name
1 Mobile operators
China Mobile
KDDI Corporation
NTT DoCoMo
Sprint Nextel
T-Mobile
Telefonica
Telecom Italia
2 Commercialization
Aplix
Noser Engineering
The Astounding Tribe
Wind River Systems
3Handset Manufacturers HTC
LG
18
Motorola
Samsung Electronics
4 Software companies
Ascender Corporation
eBay
Esmertec
LivingImage
NMS Communications
Nuance Communications
PacketVideo
SkyPop
SONIVOX
5 Semiconductor companies
Audience
Broadcom Corporation
Intel Corporation
Marvell Technology Group
Nividia Corporation
Qualcomm
SiRF Technology Holdings
Synaptics
Texas Instruments
Table 3.1: Name of the companies working for Android Application
Big guns like Nokia and Microsoft not being part of this list will mean that Android won’t
become all powerful for now. A lot will depend on the stability of the platform. Microsoft’s
19
‘windows mobile’ is not that stable, and its big selling point being integration with Microsoft
Office will be chipped away
Smart phones get increasingly popular where more and more smart phone platforms emerge.
Special attention was gained by the open source platform Android which was presented by the
Open Handset Alliance (OHA) hosting members like Google, Motorola, and HTC. Android uses
a Linux kernel and a stripped-down user land with a custom Java VM set on top. The resulting
system joins the advantages of both environments, while third-parties are intended to develop
only Java applications at the moment.
In this work, we present the benefit of using native applications in Android. Android includes
a fully functional Linux, and using it for heavy computational tasks when developing
applications can bring in substantional performance increase. We present how to develop native
applications and software components, as well as how to let Linux applications and components
communicate with Java programs. Additionally, we present performance measurements of native
and Java applications executing identical tasks.
The results show that native C applications can be up to 30 times as fast as an identical
algorithm running in Dalvik VM. Java applications can become a speed-up of up to 10 times if
utilizing JNI.
3.1 Market Predictions:
Very few but strong predictions about Android are spreading, worldwide. Firstly, Android is
going to be bigger in terms of consumer reach than its rival, the iPhone OS. It’s just because of a
true fact that it will be developed and marketed by all the 50 members of OHA, which includes
companies like Google, Samsung, HTC, Sony Ericsson, T-Mobile, Motorola, Vodafone, Sprint,
China mobile and other world leaders in telecommunication industry.
20
Fig 3.1: Smart phone market shareSecondly, Google's support will make everything possible in this Internet era, but up to now,
they hadn't started making money from their Android-based activities. On the other hand, by
2012, apart from Symbian and Android, iPhone will target its businesses development towards
its rival, the Blackberry in their segment. But predictions say that, Android is completely made
for mass market, and its lack of business features (Unlike, Winslow Mobile and Blackberry,
while both them has business exchange compatibility and PC-Synchronization features) will
create new chances for its rivals.
Fig 3.2: Platform Market Share
21
According to Gartner, Android’s smartphone market share will grow to 14 percent from less
than 2 percent by 2012, and the Symbian’s slide will continue, giving way to Android. That kind
of historical performance by Android would mirror the Apple iPhone's rule. The firstgeneration
iPhone was launched in 2007, in the U.S. and immediately, it took the world by storm. On its
release, the iPhones grabbed a good 11% of the smartphone market share in the first quarter of
2009 and continued to expand day by day. But the predictions about Android’s gathering
momentum, will overtake Apple in just 2 years. Almost all handset vendors are trying to board
the Android's bandwagon, while the Google has effectively grown a massive android developer's
community, and also, Android is backed by the America’s largest mobile network carrier, the T-
Mobile.
22
UNIT 2Analysis of
Application Software
CHAPTER 423
Unified Process
The Rational Unified Process is a Software Engineering Process. It provides a disciplined
approach to assigning tasks and responsibilities within a development organization. Its goal is to
ensure the production of high-quality software that meets the needs of its end-users, within a
predictable schedule and budget.
The Rational Unified Process is a process product, developed and maintained by Rational®
Software. The development team for the Rational Unified Process are working closely with
customers, partners, Rational's product groups as well as Rational's consultant organization, to
ensure that the process is continuously updated and improved upon to reflect recent experiences
and evolving and proven best practices.The Rational Unified Process enhances team
productivity, by providing every team member with easy access to a knowledge base with
guidelines, templates and tool mentors for all critical development activities. By having all
team members accessing the same knowledge base, no matter if you work with requirements,
design, test, project management, or configuration management, we ensure that all team
members share a common language, process and view of how to develop software.
The Rational Unified Process activities create and maintain models. Rather than focusing on the
production of large amount of paper documents, the Unified Process emphasizes the
development and maintenance of models—semantically rich representations of the software
system under development.
The Rational Unified Process is a guide for how to effectively use the Unified Modeling
Language (UML). The UML is an industry-standard language that allows us to clearly
communicate requirements, architectures and designs. The UML was originally created by
Rational Software, and is now maintained by the standards organization Object Management
Group (OMG). The Rational Unified Process is supported by tools, which automate large parts
of the process. They are used to create and maintain the various artifacts—models in particular—
of the software engineering process: visual modeling, programming, testing, etc. They are
invaluable in supporting all the bookkeeping associated with the
24
change management as well as the configuration management that accompanies each iteration.
The Rational Unified Process is a configurable process. No single process is suitable for all
software development. The Unified Process fits small development teams as well as large
development organizations.
4.1 Phases
The Unified Process is founded on a simple and clear process architecture that provides
commonality across a family of processes. Yet, it can be varied to accommodate different
situations. It contains a Development Kit, providing support for configuring the process to suit
the needs of a given organization. The Rational Unified Process captures many of the best
practices in modern software development in a form that is suitable for a wide range phases
Fig 4.1: Phases of Unified Process as compared to other process models
Inception Phase
During the inception phase, you establish the business case for the system and delimit the
project scope. To accomplish this you must identify all external entities with which the system
will interact (actors) and define the nature of this interaction at a high-level. This involves
identifying all use cases and describing a few significant ones. The business case includes
success criteria, risk assessment, and estimate of the resources needed, and a phase plan showing
dates of major milestones. The outcome of the inception phase is:
25
A vision document: a general vision of the core project's requirements, key features, and
main constraints.
A initial use-case model (10% -20%) complete).
An initial project glossary (may optionally be partially expressed as a domain model).
An initial business case, which includes business context, success criteria (revenue
projection, market recognition, and so on), and financial forecast.
An initial risk assessment.
A project plan, showing phases and iterations.
A business model, if necessary.
One or several prototypes.
Milestone : Lifecycle Objectives
At the end of the inception phase is the first major project milestone: the Lifecycle
Objectives Milestone. The evaluation criteria for the inception phase are:
Stakeholder concurrence on scope definition and cost/schedule estimates.
Requirements understanding as evidenced by the fidelity of the primary use cases.
Credibility of the cost/schedule estimates, priorities, risks, and development process.
Depth and breadth of any architectural prototype that was developed.
Actual expenditures versus planned expenditures.
The project may be cancelled or considerably re-thought if it fails to pass this milestone.
Elaboration Phase
The purpose of the elaboration phase is to analyze the problem domain, establish a sound
architectural foundation, develop the project plan, and eliminate the highest risk elements of the
project. To accomplish these objectives, you must have the “mile wide and inch deep” view of
the system. Architectural decisions have to be made with an understanding of the whole system:
its scope, major functionality and nonfunctional requirements such as performance requirements.
It is easy to argue that the elaboration phase is the most critical of the four phases. At the end
of this phase, the hard “engineering” is considered complete and the project undergoes its most
26
important day of reckoning: the decision on whether or not to commit to the construction and
transition phases. For most projects, this also corresponds to the transition from a mobile, light
and nimble, low-risk operation to a high-cost, high-risk operation with substantial inertia.
While the process must always accommodate changes, the elaboration phase activities ensure
that the architecture, requirements and plans are stable enough, and the risks are sufficiently
mitigated, so you can predictably determine the cost and schedule for the completion of the
development. Conceptually, this level of fidelity would correspond to the level necessary for an
organization to commit to a fixed-price construction phase. In the elaboration phase, an
executable architecture prototype is built in one or more iterations, depending on the scope, size,
risk, and novelty of the project. This effort should at least address the critical use cases identified
in the inception phase, which typically expose the major technical risks of the project.
While an evolutionary prototype of a production-quality component is always the goal, this
does not exclude the development of one or more exploratory, throwaway prototypes to mitigate
specific risks such as design/requirements trade-offs, component feasibility study, or
demonstrations to investors, customers, and end-users.
The outcome of the elaboration phase is:
A use-case model (at least 80% complete) — all use cases and actors have been
identified, and most usecase
descriptions have been developed.
Supplementary requirements capturing the non functional requirements and any
requirements that are not
associated with a specific use case.
A Software Architecture Description.
An executable architectural prototype.
A revised risk list and a revised business case.
A development plan for the overall project, including the coarse-grained project plan,
showing iterations” and evaluation criteria for each iteration.
An updated development case specifying the process to be used.
27
A preliminary user manual (optional).
Milestone : Lifecycle Architecture
At the end of the elaboration phase is the second important project milestone, the Lifecycle
Construction Phase
During the construction phase, all remaining components and application features are
developed and integrated into the product, and all features are thoroughly tested. The
construction phase is, in one sense, a manufacturing process where emphasis is placed on
managing resources and controlling operations to optimize costs, schedules, and quality. In this
sense, the management mindset undergoes a transition from the development of intellectual
property during inception and elaboration, to the development of deployable products during
construction and transition.
Many projects are large enough that parallel construction increments can be spawned. These
parallel activities can significantly accelerate the availability of deployable releases; they can
also increase the complexity of resource management and workflow synchronization. A robust
architecture and an understandable plan are highly correlated. In other words, one of the critical
qualities of the architecture is its ease of construction. This is one reason why the balanced
development of the architecture and the plan is stressed during the elaboration phase. The
outcome of the construction phase is a product ready to put in hands of its end-users. At
minimum, it consists of:
The software product integrated on the adequate platforms.
The user manuals.
A description of the current release.
Milestone: Initial Operational Capability
At the end of the construction phase is the third major project milestone (Initial Operational
Capability Milestone).
At this point, you decide if the software, the sites, and the users are ready to go operational,
without exposing the project to high risks. This release is often called a “beta” release.
28
The evaluation criteria for the construction phase involve answering these questions:
Is this product release stable and mature enough to be deployed in the user community?
Are all stakeholders ready for the transition into the user community?
Are the actual resource expenditures versus planned expenditures still acceptable?
Transition may have to be postponed by one release if the project fails to reach this milestone.
Transition Phase
The purpose of the transition phase is to transition the software product to the user
community. Once the product has been given to the end user, issues usually arise that require you
to develop new releases, correct some problems, or finish the features that were postponed.
The transition phase is entered when a baseline is mature enough to be deployed in the end-
user domain. This typically requires that some usable subset of the system has been completed to
an acceptable level of quality and that user documentation is available so that the transition to the
user will provide positive results for all parties.
This includes:
“beta testing” to validate the new system against user expectations
parallel operation with a legacy system that it is replacing
conversion of operational databases
training of users and maintainers
roll-out the product to the marketing, distribution, and sales teams
The primary objectives of the transition phase include:
Achieving user self-supportability
Achieving stakeholder concurrence that deployment baselines are complete and
consistent with theevaluation criteria of the vision
Achieving final product baseline as rapidly and cost effectively as practical
29
This phase can range from being very simple to extremely complex, depending on the
type of product.
4.2 Diagrams in UML
Use-Case Diagram
A use case diagram shows a set of use cases and actors and their relationship. Use case
diagrams address the static use-case view of a system. These diagrams are especially important
in organizing and modeling the behaviors of a system. Figure 4.2 illustrates the use case model
of sms scheduler application.
Fig 4.2 shows the use case diagram of our application SMS Scheduler. This diagram consist
of actor, use cases & interface .There are three actors one is user and another is system and final
is service provider different use cases this ellipse are representing this use cases and lines are
showing relationship between actor and use-cases. For our application we used three packages
(application database, message interface, application database). For example we can see that user
is selecting message typing and the selecting contact and finally entering the schedule date and
time and second actor system is running the timer and sending it to the service provider.
30
Fig 4.2: Use Case Diagram of SMS Scheduler
31
Class Diagram
A class diagram shows a set of classes, interfaces, and collaborations and their relationships.
These diagrams are the most common diagram found in modeling Object-oriented system. Class
diagrams address the static design view of a system. Class diagrams that include active classes
address the static process view of a system. Component diagrams are variants of class diagrams.
Fig 4.3 represents a class diagram there are four classes (system, user, database &service
provider) and database is the main class which contains all the information through with other
classes are related and accessing their operation
Fig 4.3: Class Case Diagram of SMS Scheduler.
State Diagram
32
A state diagram shows a state machine, consisting of states, transitions, events and activities.
A state diagram shows the dynamic view of an object. They are especially important in modeling
the behavior of an interface, class, or collaboration and emphasize the event ordered behavior of
an object, which is especially useful in modeling reactive systems
Collaboration & Sequence diagram
Sequence diagram is a kind of an interaction diagram .Interaction diagram shows an
interaction, consisting of a set of object or roles, including the messages that may be dispatched
among them. It address the dynamic view of a system. A sequence diagram is an interaction
diagram that emphasizes the time ordering of messages.
33
UNIT 3Development of
Application Software
CHAPTER 5Android Framework Activities
34
Android applications are written in the Java programming language. The Android framework
provides everything necessary to implement an average application. The Android application
lifecycle involves the following key components:
Activities are functions the application performs.
Groups of views define the application’s layout.
Intents inform the system about an application’s plans.
Services allow for background processing without user interaction.
Notifications alert the user when something interesting happens.
Android Applications can interact with the operating system and hardware using a collection
of managers. Each manager is responsible for keeping the state of some system service. For
example, there is a LocationManager that facilitates interaction with the location-based services
available on the handset. The ViewManager and WindowManager manage user interface
fundamentals. Applications can interact with one another by using or acting as a
ContentProvider. Built-in applications such as the Contact manager are content providers,
allowing third-party applications to access contact data and use it in an infinite number of ways.
5.1 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” (serves as an interface for
interaction with the user like buttons, checkbox and text-entry fields). The ViewGroup class
serves as the base for subclasses called "layouts," which offer different kinds of layout
architecture, like linear, tabular and relative.
35
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. View is also a
point of interaction for the user and the receiver of the interaction events.
View Hierarchy
An Activity's User Interface can be defined on the Android platform by using a hierarchy of
View and ViewGroup nodes, as shown in the diagram below. This hierarchy tree can be as
simple or complex, and it can be build using Android's set of predefined widgets and layouts, or
with custom Views.
Fig 5.1 View Hierarchy
In order to attach the view hierarchy tree to the screen, 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. The children may
request a size and location within the parent, but the parent object has the final decision on where
how big each child can be.
5.2 Application Components
36
The VM is not a JVM , but is the Dalvik Virtual Machine, an open source technology. Each
Android application runs within an instance of the Dalvik VM, which in turn resides within a
Linux-kernel managed process, as shown in Fig.5.2
Fig 5.2 Dalvik VM
An Android application consists of one or more of the following classifications:
Activities
An application that has a visible UI is implemented with an activity. When a user selects an
application from the home screen or application launcher, an activity is started.
Services
A service should be used for any application that needs to persist for a long time, such as a
network monitor or update-checking application.
Content providers
Content provider can be treated as a database server. A content provider's job is to manage
access to persisted data, such as a SQLite database. If the application is very simple, user might
not necessarily create a content provider. If user is building a larger application, or one that
37
makes data available to multiple activities or applications, a content provider is the means of
accessing your data.
CHAPTER 6Development of an Android Application
38
An Android application is described the file "AndroidManifest.xml". This files contains all
classes of the application and the required permissions for the application, e.g. if the application
requires network access. "AndroidManifest.xml" can be thought as the deployment descriptor for
an Android application. An Android application consists of the following parts:
Activity - A screen in the Android application
Intent / Broadcast Receiver - allow the application to request and / or provide services from
other application. For example the application call asks via intent for a contact application.
Application register themself via an IntentFilter
Services - Background activities without UI
Content Provider - provides data to applications, Android contains a SQLLite DB which can
serve as data provider
The Android Development Tools (ADT) plugin for Eclipse adds powerful extensions to the
Eclipse integrated development environment. It allows us to create and debug Android
applications easier and faster. If we use Eclipse, the ADT plugin gives us an incredible boost in
developing Android applications:
It gives you access to other Android development tools from inside the Eclipse IDE. For
example, ADT lets you access the many capabilities of the DDMS tool: take screenshots,
manage port-forwarding, set breakpoints, and view thread and process informationd irectly
from Eclipse.
It provides a New Project Wizard, which helps you quickly create and set up all of the basic
files needed for a new Android application.
It automates and simplifies the process of building your Android application.
It provides an Android code editor that helps you write valid XML for your Android manifest
and resource files. 39
It will even export your project into a signed APK, which can be distributed to users.
6.1 Development of an Android Application
ADT plug-in provides a New Project wizard for the development of an android application.
There are certain steps for creating an application:
1. Select File > New > Project.
2. Select Android > Android Project, and click Next.
3. Select the contents for the project:
Enter a Project Name: This will be the name of the folder where your project is created. Under
Contents, select Create new project in workspace. Select your project workspace location.
Under Target, select an Android target to be used as the project's Build Target. The Build Target
specifies which Android platform you'd like your application built against. Unless you know that
you'll be using new APIs introduced in the latest SDK, you should select a target with the lowest
platform version possible, such as Android 1.1. Under Properties, fill in all necessary fields.
Enter an Application name. This is the human-readable title for your application — the
name that will appear on the Android device.
Enter a Package name. This is the package namespace (following the same rules as for
packages in the Java programming language) where all your source code will reside.
Select Create Activity (optional, of course, but common) and enter a name for your main
Activity class.
Enter a Min SDK Version. This is an integer that indicates the minimum API Level
required to properly run your application. Entering this here automatically sets the
minSdkVersion attribute in the <uses-SDK> of your Android Manifest file. If you're
unsure of the appropriate API Level to use, copy the API Level listed for the Build Target
you selected in the Target tab.
40
Click Finish
6.2 Running of an Android Application:
For the execution of an android application we need an Android virtual device .It specifies
the android platform to be used on emulator .With ADT 0.9.3, the Android SDK and AVD
Manager provides a simple graphical interface for creating and managing AVDs.
To create an AVD with the AVD Manager:
1. Select Window > Android SDK and AVD Manager, or click the Android SDK and AVD
Manager icon (a black device) in the Eclipse toolbar.
2. In the Virtual Devices panel, you'll see a list of existing AVDs. Click New to create a new
AVD.
3. Fill in the details for the AVD. Give it a name, a platform target, an SD card image
(optional), and a skin (HVGA is default).
4. Click Create AVD.
After creating an AVD we can select run option from the eclipse main menu it will create
default launch configuration for the project when you choose to run or debug your application,
Eclipse will perform the following:
1. Compile the project (if there have been changes since the last build).
2. Create a default launch configuration (if one does not already exist for the project).
3. Install and start the application on an emulator or device (based on the Deployment Target
defined by the run configuration).
6.3 Creating a Running Configuration
41
The run configuration specifies the project to run, the Activity to start, the emulator options to
use, and so on. When you first run a project as an Android Application, ADT will automatically
create a run configuration. The default run configuration will launch the default project Activity
and use automatic target mode for device selection (with no preferred AVD). If the default
settings don't suit our project, we can customize the launch configuration or even create a new.
To create or modify a launch configuration, follow these steps as appropriate for your Eclipse
version:
Open the run configuration manager.
In Eclipse 3.3 (Europa), select Run > Open Run Dialog (or Open Debug Dialog)
In Eclipse 3.4 (Ganymede), select Run > Run Configurations (or Debug
Configurations)
Expand the Android Application item and create a new configuration or open an existing one.
To create a new configuration:
Select Android Application and click the New launch configuration icon above the list
(or, right-click Android Application and click New).
Enter a Name for your configuration.
In the Android tab, browse and select the project you'd like to run with the configuration.
To open an existing configuration, select the configuration name from the list nested below
Android Application.
Adjust your desired launch configuration settings. In the Target tab, consider whether you'd like
to use Manual or Automatic mode when selecting an AVD to run our application. See the
following section on Automatic and manual target modes).
42
We can specify any emulator options to the Additional Emulator Command Line Options
field. For example, we could add -scale 96dpi to scale the AVD's screen to an accurate size,
based on the dpi of your computer monitor. For a full list of emulator options, see the Android
Emulator document.
Automatic and manual target modes
By default, a run configuration uses the automatic target mode in order to select an AVD. In this
mode, ADT will select an AVD for the application in the following manner:
If there's a device or emulator already running and its AVD configuration meets the
requirements of the application's build target, the application is installed and run upon it.
If there's more than one device or emulator running, each of which meets the requirements
of the build target, a "device chooser" is shown to let you select which device to use.
If there are no devices or emulators running that meet the requirements of the build target,
ADT looks at the available AVDs. If one meets the requirements of the build target, the
AVD is used to launch a new emulator, upon which the application is installed and run.
If all else fails, the application will not be run and you will see a console error warning you
that there is no existing AVD that meets the build target requirements.
6.4 Executing arbitrary Java expressions in Eclipse
We can execute arbitrary code when paused at a breakpoint in Eclipse. For example, when in
a function with a String argument called "zip", you can get information about packages and call
class methods. You can also invoke arbitrary static methods: for example, entering
android.os.Debug.startMethodTracing() will start dmTrace.
Open a code execution window, select Window>Show View>Display from the main menu to
open the Display window, a simple text editor. Type your expression, highlight the text, and
43
click the 'J' icon (or CTRL + SHIFT + D) to run your code. The code runs in the context of the
selected thread, which must be stopped at a breakpoint or single-step point.
If you suspend the thread manually, you have to single-step once; this doesn't work if the
thread is in Object.wait(). If you are currently paused on a breakpoint, you can simply highlight
and execute a piece of source code by pressing CTRL + SHIFT + D. You can highlight a block
of text within the same scope by pressing ALT +SHIFT + UP ARROW to select larger and
larger enclosing blocks, or DOWN ARROW to select smaller blocks. Here are a few sample
inputs and responses in Eclipse using the Display window.
Input Response
Zip (java.lang.String)
/work/device/out/linux-x86-debug/android/app/android_sdk.
zip
zip.endsWith(".zip
")
(boolean) true
zip.endsWith(".jar"
)
(boolean) false
Table 6.1: Sample inputs and responses in Eclipse using the Display window
You can also execute arbitrary code when not debugging by using a scrapbook page. Search
the Eclipse documentation for "scrapbook".
44
CHAPTER 7Publishing an Android Application on Android Market
This chapter shows how to publish any application on the Android Market. It enlists the
various steps to be performed in order to successfully publish any application. The online
application store concept took off with the Apple iPhone App Store and since then every major
platform has come up with an application store. Google launched their Android Market some
months back and it has been a huge hit. There are many advantages of an application being on
Android Market - it gives the application more exposure and one can directly sell his application
to a huge user base for a small fee without setting up any infrastructure. Following is the basic
that should be taken care of before you publish your application on the Android Market.
7.1 Testing the Android Application to be published
The application must be extensively tested on both the emulator and a wide range of devices
(that shouldn't be a big problem right now as there are only 2 Android devices available) before
moving on to the next step. Performance, responsiveness and compatibility with each device
should be checked. The SDK comes bundled with many tools like
DDMS (Dalvik Debug Monitor Service) - To manage processes, debug the application
and generate trace data.
Trace View - To generate graphical analysis views of the trace data of the application.
UI / Application Exerciser Monkey - To stress test the Android applications by
emulating a random sequence of clicks, touches, gestures and other events and then
monitoring the response and performance.45
7.2 Specify the Name, Icon and Version of the Android Application
Specify all the relevant data about the application in the Manifest file. You should specify all
the relevant data pertaining to the application in the AndroidManifest.xml file at the root
directory of your APK application package. The important details are:
1. Android-icon - This specifies the icon to be displayed as the application's icon. The icon is
the visual representation of the application. It is displayed everywhere - the Menu, Android
Market, Manage Applications, My Downloads etc. Make sure to choose a visually appealing
icon; after all the first impressions is the last impression.
2. Android-label - This specifies the name of your application. It is also displayed almost
everywhere the icon is - Android Market, Manage Applications, My Downloads etc.
3. Android-version-Code - Specifying the version is a very important step before publishing the
application. Versions are only used by the system when upgrading / downgrading.
4. Android-version-Name - This specifies the actual version number of the application. It is
used only to display the version to the users. It can be of the form 1.2.2, 1.3.3.1 etc.
7.3 Sign the Android Application
As you begin developing Android applications, understand that all Android applications must
be digitally signed before the system will install them on an emulator or an actual device. There
are two ways to do this: with a debug key (for immediate testing on an emulator or development
device) or with a private key (for application distribution).
The ADT plugin helps you get started quickly by signing your .apk files with a debug key,
prior to installing them on an emulator or development device. This means that you can quickly
run your application from Eclipse without having to generate your own private key. No specific
action on your part is needed, provided ADT has access to Key tool. However, note that if you
46
intend to publish your application, you must sign the application with your own private key,
rather than the debug key generated by the SDK tools. Read Signing Your Applications, which
provides a thorough guide to application signing on Android and what it means to you as an
Android application developer. The document also includes a guide to exporting and signing
your application with the ADT's Export Wizard.
The Android system requires that all installed applications be digitally signed with a
certificate whose private key is held by the application's developer. The Android system uses the
certificate as a means of identifying the author of an application and establishing trust
relationships between applications. The certificate is not used to control which applications the
user can install.
Figure7.1 Signing android Application using a default debug keystore.
The certificate does not need to be signed by a certificate authority: it is perfectly allowable,
and typical, for Android applications to use self-signed certificates (using the KEYTOOL tool
built into Java Development Kit). After obtaining the key, APK application package can be
47
signed using the JARSIGNER tool. When an application is ready to release for end-users, it must
signed with a suitable private key. The system will not install an application that is not signed.
An application which is signed with the debug key generated by the SDK tools can not
published. The system tests a signer certificate's expiration date only at install time. If an
application's signer certificate expires after the application is installed, the application will
continue to function normally. Standard tools like Keytool and Jarsigner can be used to generate
keys and sign application .apk files. Once the application is signed, the zipalign tool is used to
optimize the final APK package.
To sign an application manually, one needs to perform the following steps:
1. Compile the application in release signing mode. To do so in Eclipse, Export Unsigned;
right-click on the package name and select Android Tools Application Package.
Figure 7.2: Using Eclipse: Exporting an Android application in release signing model.
2. Select a directory for exporting the application (Android package has the .apk extension). For
example, in figure 4 the Android package is exported to C:\Program Files\Java\jdk1.6.0_10\
bin\.
48
Figure 7.3: The Directory Path: Exporting an .apk file.
3. For signing the application using the debug keystore, copy the Debug.keystore file from
C:\Documents and Settings\\Local Settings\Application Data\Android\ to C:\Program Files\
Java\jdk1.6.0_10\bin\.
4. Use the jarsigner.exe tool (comes with your JDK) located in C:\Program Files\Java\
jdk1.6.0_10\bin\ to sign the .apk file with the specified keystore:
jarsigner -verbose -keystore debug.keystore MyKillerApp.apk androiddebugkey
When prompted for the password for the keystore, use the default password: android.The
jarsigner.exe tool takes in the following options:
a) -keystore: This is the name of the keystore containing your private key.
b) -verbose: This enables verbose output.
49
Figure 7.4. Signed with the Keystore: Signing the .apk file with debug.keystore.
The alias for the debug.keystore file is androiddebugkey. Figure 4.4 shows the application
signed with the debug.keystore default keystore.
50
Figure 7.5. Verified and Certified: Verifying that the application was signed correctly.
To verify that the application is signed correctly, you can use the –verify option with
jarsigner.exe. You can also use the –certs option to view the details of the certificate used to sign
the application (see 7.5).
Generating Own Key: One can generate his own certificate by using the keytool.exe tool (this
also comes with your JDK). To generate one’s own certificate, issue the following command:
keytool –genkey –v –keystore learn2develop.keystore –alias learn2develop –keyalg RSA –
validity 10000
51
The above command generates a certificate named learn2develop.keystore with the key alias
learn2develop, generated using the RSA algorithm, and with a validity of 10,000 days (this is the
minimum recommended). Request for some information will be prompted (see figure 4.6).
Figure 7.6: Prompting
In particular, supplying a password for the keystore and a password for the private key will
be asked. If one is publishing his application for the Android Market, your keystore must have a
validity period ending after 22 October 2033. Secure and protect these two passwords so that
only people who are authorized to sign the applications know about them.
52
Figure 7.7: The learn2develop.keystore File
Once the learn2develop.keystore file is generated, application can be signed with it (see
figure 4.7).
7.4 Deploying .apk Files
Once the Android application is signed, deploying them to emulators and devices using the
adb.exe tool (located in the tools folder of the Android SDK) can be done. For illustration, copy
the MyKillerApp.apk created (and signed) in the previous section to the android-sdk-windows-
1.0_r1\tools folder. To install the application to an emulator (assuming the emulator is currently
up and running), issue the following command:
adb install MyKillerApp.apk
53
Figure 7.8: MyKillerApp.apk; Installing an Android .apk file using adb.
To remove an installed application using the adb tool, the shell option is used. To remove an
application from its installed folder, follow this:
adb shell rm /data/app/net.learn2develop.MyKillerApp.apk
Another way of deploying an application is to use the DDMS tool in Eclipse (see Figure 10).
With an emulator (or device) selected, use the File Explorer in DDMS to go to the /data/app
folder and use the "Push a file onto the device" button to copy the .apk file into the device.
Figure 7.9: Using the DDMS Copying an .apk file into the emulator using the DDMS tool.
54
Once this is done, the application will automatically appear on the device (see figure 7.10).
Figure 7.10: It Works! Locating the newly installed Android application.
7.5 Publishing Updates on Android Market
At any time after publishing an application on Android Market, you can upload and publish
an update to the same application package. When you publish an update to an application, users
who have already installed the application will automatically receive a notification that an update
is available for the application. They can then choose to update the application to the latest
version.Before uploading the updated application, be sure that you have incremented the
android:versionCode and android:versionName attributes in the <manifest> element of the
manifest file. Also, the package name must be the same and the .apk must be signed with the
same private key. If the package name and signing certificate do not match those of the existing
version, Market will consider it a new application and will not offer it to users as an update.
55
UNIT 04
Hands on Activities
56
CHAPTER8SMS Sending & Receiving Application Based on Android
It would be safe to say that nearly every mobile phone sold in the past decade has SMS
messaging capabilities. In fact, SMS messaging is one great killer application for the mobile
phone and it has created a steady revenue stream for mobile operators. Understanding how to use
SMS messaging in your application can provide you with many ideas to create the next killer
application.
In this article, we take a look at how you can programmatically send and receive SMS
messages in your Android applications. The good news for Android developers is that you don't
need a real device to test out SMS messaging - the free Android emulator provides the capability
to do so.
8.1 Sending SMS Messages
Android uses a permission-based policy where all the permissions needed by an application
need to be specified in the AndroidManifest.xml file. By doing so, when the application is
installed it will be clear to the user what specific access permissions are required by the
application. For example, as sending SMS messages will potentially incur additional cost on the
user's end, indicating the SMS permissions in the AndroidManifest.xml file will let the user
decide whether to allow the application to install or not.
To get started, first launch Eclipse and create a new Android project. Name the project as
shown in Figure 8.1.
57
Fig 8.1 Creating a new Android project using Eclipse
8.2 UI for sending messages
In the AndroidManifest.xml file, add the two permissions - SEND_SMS and
RECEIVE_SMS:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.learn2develop.SMSMessaging"
android:versionCode="1"
android:versionName="1.0.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SMS"58
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>
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
</manifest>
In the main.xml file located in the res/layout folder, add the following code so that the user
can enter a phone number as well as a message to send:
<?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="Enter the phone number of recipient"
/>
59
<EditText
android:id="@+id/txtPhoneNo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Message"
/>
<EditText
android:id="@+id/txtMessage"
android:layout_width="fill_parent"
android:layout_height="150px"
android:gravity="top"
/>
<Button
android:id="@+id/btnSendSMS"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Send SMS"
/>
</LinearLayout>
The above code creates the UI shown in Figure 8.2
60
Fig 8.2 Creating the UI for sending SMS messages
Next, in the SMS activity, we wire up the Button view so that when the user clicks on it, we
will check to see that the phone number of the recipient and the message is entered before we
send the message using the sendSMS() function, which we will define shortly:
8.3 Package net.learn2develop.SMSMessaging;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SMS extends Activity
{
Button btnSendSMS;
61
EditText txtPhoneNo;
EditText txtMessage;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtMessage = (EditText) findViewById(R.id.txtMessage);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String phoneNo = txtPhoneNo.getText().toString();
String message = txtMessage.getText().toString();
if (phoneNo.length()>0 && message.length()>0)
sendSMS(phoneNo, message);
else
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
});
}
}
62
The sendSMS() function is defined as follows:
public class SMS extends Activity
{
//...
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
//...
}
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, SMS.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
}
To send an SMS message, we use the SmsManager class. Unlike other classes, you do not
directly instantiate this class; instead we will call the getDefault() static method to obtain an
SmsManager object. The sendTextMessage() method sends the SMS message with a
PendingIntent. The PendingIntent object is used to identify a target to invoke at a later time. For
example, after sending the message, we can use a PendingIntent object to display another
63
activity. In this case, the PendingIntent object (pi) is simply pointing to the same activity
(SMS.java), so when the SMS is sent, nothing will happen.
If we need to monitor the status of the SMS message sending process, you can actually use
two PendingIntent objects together with two BroadcastReceiver objects, like this:
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
64
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
65
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
The above code uses a PendingIntent object (sentPI) to monitor the sending process. When
an SMS message is sent, the first BroadcastReceiver's onReceive event will fire. This is where
you check the status of the sending process. The second PendingIntent object (deliveredPI)
monitors the delivery process. The second BroadcastReceiver's onReceive event will fire when
an SMS is successfully delivered.
We can now test the application by pressing F11 in Eclipse. To send an SMS message from
one emulator instance to another, simply launch another instance of the Android emulator by
going to the Tools folder of the SDK and running Emulator.exe.
66
Fig 8.3 Sending an SMS message
Figure shows how we can send an SMS message from one emulator to another; simply use
the target emulator's port number (shown in the top left corner of the window) as its phone
number. When an SMS is sent successfully, it will display a "SMS sent" message. When it is
successfully delivered, it will display a "SMS delivered" message. Note that for testing using the
emulator, when an SMS is successfully delivered, the "SMS delivered" message does not appear;
this only works for real devices.
Figure shows the SMS message received on the recipient emulator. The message first
appeared in the notification bar (top of the screen). Dragging down the notification bar reveals
the message received. To view the entire message, click on the message.
67
Fig 8.4 The SMS message received by the Android emulator
If we do not want to go through all the trouble of sending the SMS message yourself, you can
use an Intent object to help you send an SMS message. The following code shows how you can
invoke the built-in SMS application to help you send an SMS message:
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "Content of the SMS goes here...");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
Figure 8.5 shows the built-in SMS application invoked to send the SMS message.
68
Figure 8.5 Invoking the built-in SMS application
8.4 Receiving SMS Messages
To see how to receive SMS messages from within your Android application, in the
AndroidManifest.xml file add the <receiver> element so that incoming SMS messages can be
intercepted by the SmsReceiver class:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.learn2develop.SMSMessaging"
android:versionCode="1"
android:versionName="1.0.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SMS"
android:label="@string/app_name">
69
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SmsReceiver">
<intent-filter>
<action android:name=
"android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
</manifest>
Add a new class file to your project and name it as SmsReceiver.java (see Figure 6).
Figure 8.6: Adding the SmsReceiver.java file to the project
70
In the SmsReceiver class, extend the BroadcastReceiver class and override the onReceive()
method:
package net.learn2develop.SMSMessaging;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class SmsReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
}
}
When SMS messages are received, the onCreate() method will be invoked. The SMS
message is contained and attached to the Intent object (intent - the second parameter in the
onReceive() method) via a Bundle object. The messages are stored in an Object array in the PDU
format. To extract each message, you use the static createFromPdu() method from the
SmsMessage class. The SMS message is then displayed using the Toast class:
package net.learn2develop.SMSMessaging;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver
71
{
@Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
That's it! To test the application, press F11 in Eclipse. Deploy the application to each
Android emulator. Figure 7 shows Eclipse showing the emulators currently running. All you
need to do is to select each emulator and deploy the application onto each one.
72
Figure 8.7: Selecting an emulator/device to deploy the application onto
Figure 8.8 shows that when you send an SMS message to another emulator instance (port
number 5556), the message is received by the target emulator and displayed via the Toast class.
Fig 8.8: Sending and receiving SMS messages using the Android emulators
73
This article shows how we can send and receive SMS messages programmatically from
within your Android application. The capability to send and receive SMS messages is very
useful as we can build very compelling applications. As an example, we can build a location
tracker application where you can send a secret-coded SMS message to a device and when the
device receives the secret SMS message it will reply with another SMS message containing its
current geographical location using its built-in GPS receiver.
CHAPTER9Conclusion
74
Android has come a long way since its inception three years ago. It will surely impact the
mobile market when the Android phones are released, but also provides an excellent opportunity
for developers to enter the mobile market. A great deal can be learned by both creating
applications using Android's unique Java API as well as attempting to port Android to real
hardware. The classroom cans befit from Android, given the amount of resources available for
reference.
Given the market trend towards the mobile market, future developers can greatly benefit by
using Android to improve their algorithms and resource management. Since it is open source,
there is no cost to learn. Android is a win-win situation for both the community and developers.
Android will be bigger in terms of pure numbers (reach) than the iPhone OS. Simply because
of the fact that it will eventually be available on a whole host of phones as opposed to just the
iPhone.
We have shown how to send and receive SMS messages programmatically from within your
Android application. The capability to send and receive SMS messages is very useful as we can
build very compelling applications. As an example, we can build a location tracker application
where you can send a secret-coded SMS message to a device and when the device receives the
secret SMS message it will reply with another SMS message containing its current geographical
location using its built-in GPS receiver.
Apart from Google, Apps developers and vendors are predicted to be the major beneficiaries,
since they would make most out of the Android with its wider market structure backed by all the
members of OHA, developing different versions of Android, and driving the Android's apps
market to a new edge, defeating all the others.
CHAPTER 10Bibliography
75
Web References
http://code.google.com/p/android-on-n8xx/wiki/Home
http://www.openhandsetalliance.com/
http://www.andev.org
http://www.android.com
http://www.phandroid.com
http://code.google.com/android
http://elinux.org/Android_on_OMAP
http://wiki.openembedded.net/index.php
http://www.ok-labs.com/products/product-strategy/secure-hypercell-technology
http://www.economist.com/displaystory.cfm?story_id=12304882&fsrc=nwl
http://news.cnet.com/8301-17938_105-10047551-1.html
http://code.google.com/android/adc_gallery/
76
Recommended