Professional Documents
Culture Documents
murachs
Android
programming
(Chapter 1)
Thanks for downloading this chapter from Murachs Android Programming. We hope
it will show you how easy it is to learn from any Murach book, with its paired-pages
presentation, its how-to headings, its practical coding examples, and its clear, concise
style.
To view the full table of contents for this book, you can go to our web site. From there,
you can read more about this book, you can find out about any additional downloads that
are available, and you can review our other books on related topics.
Thanks for your interest in our books!
If youre a Java virgin like I was before reading this book, then youre going to
love it. I had a development environment up & running within half an hour and
was dabbling with code 15 minutes after that!
Andy Bonner, vbcity.com
One of the things I really like is that this book uses an IDE to teach Java to the
next generation of programmers. Any professional programmer will tell you
that an IDE is absolutely essential in making you more productive.
John Yeary, Java Evangelist
Ever have someone come in your office with a Java question, and you
reach for a certain book that you know has the answer in it? Murachs Java
Programming supplies these answers, both quickly and completely. If this book
isnt on your bookshelf, you should get it there.
Robert Liguori, Tech Center Java User Group
Another thing I like is the exercises at the end of each chapter. They reinforce
the main points and force you to get your hands dirty.
Hien Luu, SD Forum/Java SIG
Section 1
Get started fast with Android
This section gets you started fast with Android programming. Chapter
1 introduces you to some important terms, concepts, and background
information. Chapter 2 shows you how to use Eclipse to work with Android
projects. Chapter 3 introduces you to the basic skills that you need for
developing Android apps. And chapter 4 shows you how to test and debug
Android apps.
To illustrate these skills, this section shows how to write, test, and
debug a simple Tip Calculator app. This app calculates the tip you would
give based on the amount of a bill. When you complete these chapters,
youll be able to write, test, and debug simple applications of your own.
1
An introduction to Android
This chapter introduces you to the concepts and terms that you need for
developing Android apps. To give you a clear idea of how the code for an
Android app works, this chapter presents some of the code for a simple app
that calculates tips. When you finish this chapter, youll be ready to get started
with Android development.
Android overview....................................................................4
Types of devices................................................................................................4
Types of apps....................................................................................................6
A brief history...................................................................................................8
Versions...........................................................................................................10
System architecture........................................................................................12
How apps are compiled and run.....................................................................14
Perspective............................................................................30
Section 1
Android overview
Android is a Linux-based operating system designed primarily for touchscreen mobile devices such as smartphones and tablet computers. Before you
begin developing apps that run on Android, its helpful to take a moment to
consider the types of Android devices and apps that are available today. In addition, its helpful to understand the history, versions, and architecture of Android.
Types of devices
Figure 1-1 starts by showing two of the most popular Android devices, a
smartphone and a tablet. However, the code for Android is open-source. As a
result, it can be customized to work with other types of electronic devices such
as eBook readers, cameras, home automation systems, home appliances, vehicle
systems, game consoles, and so on.
Chapter 1
An introduction to Android
Readers
Cameras
Home automation systems
Home appliances
Vehicle systems
Game consoles
Description
Android is a Linux-based operating system designed primarily for touchscreen
mobile devices such as smartphones and tablet computers.
Since the code for Android is open-source, it can be customized to work with other
types of electronic devices.
Figure 1-1
Section 1
Types of apps
Android has a large community of developers writing applications, more
commonly referred to as apps, that extend the functionality of Android devices.
Figure 1-2 lists some categories of different types of apps and describes some
of the functionality available from each category. As you review this list, keep
in mind that these categories are only intended to give you a general idea of the
various types of Android apps. More categories exist, and the functionality thats
available from Android apps is constantly expanding.
If you have used a smartphone or tablet, you should be familiar with some
of the apps listed in this figure. For example, you probably use apps to send and
receive text messages and email. You probably use apps to take pictures, listen to
music, and watch video. You probably use apps to get directions and navigate to
a location. You probably use apps to check the weather, read news, and browse
the web.
In addition, you may use apps from social media companies like Facebook
and Twitter to work with social media. You may use apps to play games like
Angry Birds. The main point here is that there are many different types of apps
and that application developers are constantly creating new apps that use the
capabilities of Android phones in new ways.
Some apps come preinstalled on the device. For example, most phones
include apps for managing contacts, using the phone, sending and receiving text
messages and email, working with photos and video, and web browsing. Other
apps are available for download through Google Play or third-party sites. Some
apps are free. Other apps are expensive. All apps were created by somebody like
you who learned how to develop Android apps.
Chapter 1
An introduction to Android
Send and receive text messages, send and receive email, make and
receive phone calls, manage contacts, browse the web.
Photography
Audio
Video
Weather
News
Personalization
Productivity
Finance
Manage bank accounts, make payments, manage insurance policies, manage taxes, manage investment portfolio.
Business
Books
Reference
Education
Shopping
Social
Fitness
Sports
Travel
Games
Description
Android has a large community of developers writing applications, more
commonly referred to as apps, that extend the functionality of Android devices.
Android apps are available for download through Google Play or third-party sites.
Figure 1-2
Section 1
A brief history
Figure 1-3 summarizes the history of Android. In 2003, a handful of entrepreneurs in Palo Alto, California, founded Android, Inc. In 2005, Google bought
Android, Inc. Then, in 2007, the Open Handset Alliance was announced. This
alliance consists of a consortium of hardware, software, and telecommunication
companies devoted to advancing open standards for mobile devices. That same
year, Google released Android code as open source under the Apache License. In
addition, Google helped to create the Android Open Source Project (AOSP) and
put it in charge of the maintenance and further development of Android.
In 2008, the first version of the Android Software Development Kit (SDK)
was released. This SDK contains all of the tools that Android developers need to
develop apps. Later in 2008, the first Android phones became available.
Since 2008, new versions of the Android SDK have continued to be released,
and Android devices have continued to proliferate. During that time, hundreds
of thousands of apps have been developed, and billions of apps have been
downloaded.
Chapter 1
An introduction to Android
2005
Google releases Android code as open source under the Apache License.
2009-present
Description
Android has grown steadily since its release in 2008 until the present.
Figure 1-3
10
Section 1
Versions
Figure 1-4 describes all major releases of Android starting with version 1.6
and ending with version 4.3. Here, each version of Android corresponds with
an API (Application Programming Interface) number. For example, version 4.2
corresponds with API 17, and version 2.2 corresponds with API 8. In addition,
each version has a code name thats based on something sweet. For example,
version 2.2 carries the code name Froyo, while version 4.1 is known as Jelly
Bean.
As you develop an Android app, you must decide the minimum API level
that your app supports. As of April 2013, many developers choose 7 or 8 as the
minimum API level to support since that covers a high percentage of all Android
devices.
The distribution percentages shown here are from April 2013. As time
progresses, more users will upgrade from older devices to newer ones. As a
result, you should check the URL shown in this figure to get current percentages
before you decide the minimum API level for your app.
As you review this figure, you may notice that it doesnt include some
versions of Android such as 1.0 and 1.1. Thats because there are virtually no
devices left that run on these versions of Android. As time marches on, its
inevitable that the same fate will befall other older versions of Android too.
Chapter 1
An introduction to Android
Android versions
Version
Code name
API
Release year
Distribution
1.6
Donut
0.1%
2.1
Eclair
1.7%
2.2
Froyo
2.3 - 2.3.2
Gingerbread
2010
4.0%
0.1%
2.3.3 - 2.3.7
10
39.7%
3.2
Honeycomb
13
4.0.3 - 4.0.4
15
29.3%
4.1
Jelly Bean
16
23.0%
2011
2012
0.2%
4.2
17
2.0%
4.3
18 2013
0%
Description
Many new versions of Android were released from 2009 to 2012.
The distribution percentages in this figure are from April 2013. To get current
percentages, please visit the URL shown above.
As you develop an Android app, you must decide the minimum API level that
your app supports. As of April 2013, many developers choose Android 2.2 as the
minimum API level to support since that covers a high percentage of all Android
devices.
Figure 1-4
Android versions
11
12
Section 1
System architecture
Figure 1-5 shows the Android system architecture, which is also known as
the Android stack. This stack has four layers.
The bottom layer of the stack is Linux, an open-source operating system
thats portable and secure. This operating system provides low-level drivers for
hardware, networking, file system access, and inter-process communication
(IPC).
The second layer up in the stack contains the native libraries. These libraries
are written in C or C++. They include the Dalvik virtual machine (VM), which
works similarly to the Java virtual machine (JVM). However, the Dalvik VM
was designed specifically for mobile devices and their inherent limitations, such
as battery life and processing power.
The third layer up in the stack contains the application framework. This
layer is written mostly in Java, and it provides libraries that can be used by the
top layer of the stack. In this book, youll learn how to use some of these libraries, such as the libraries for the notification manager, content providers, and the
location manager.
The top layer of the stack contains Android apps. These apps include
pre-installed apps such as the apps that you can use to manage the home screen,
manage your contacts, make and receive calls, browse the web, and so on. In
addition, these apps include other apps that you can download and install. These
types of apps are written in Java, and they are the type of apps that youll learn
to develop in this book.
Chapter 1
An introduction to Android
Android stack
Description
Linux is an open-source operating system thats portable and secure.
The native libraries are written in C or C++. These libraries provide services to the
Android application layer.
The Dalvik virtual machine (VM) works similarly to the Java virtual machine
(JVM). However, the Dalvik VM was designed specifically for mobile devices and
their inherent limitations such as battery life and processing power.
The application framework provides libraries written in Java that programmers can
use to develop Android apps.
Figure 1-5
13
14
Section 1
Chapter 1
An introduction to Android
Description
When you develop an Android app, you typically use an IDE (Integrated
Development Environment) such as Eclipse to create a project, and you typically
use Java as the programming language.
When you develop an Android app, you can run it on a physical Android device,
such as a smartphone or tablet. Or, you can run it on an emulator, which is a
piece of software that runs on your computer and acts like an Android device. An
Android emulator can also be called an Android Virtual Device (AVD).
Before you can run a project, you must build the project. Typically, the IDE automatically builds a project before running it.
When the IDE builds a project, it compiles the Java source code (.java files) into
Java bytecodes (.class files) and then into Dalvik executable files (.dex files). Dalvik
executable files can be run by the Dalvik virtual machine thats available from all
Android devices.
When the IDE builds a project, it puts the files for the project into an Android
package (.apk file). This file contains all of the files necessary to run your app on a
device or emulator including the .dex files, compiled resources (the resources.arsc
file), uncompiled resources, and a binary version of the AndroidManifest.xml file.
To run an app on an emulator or device, the app must be signed with a digital
certificate that has a private key. During development, the IDE automatically signs
the app for you in debug mode using a special debug key. Before you release an
app, you must sign the app in release mode, using your own private key. For more
information about this, please see chapter 17.
The Android debug bridge (ADB) lets your IDE communicate with an emulator or a
physical Android device.
Figure 1-6
15
16
Section 1
Chapter 1
An introduction to Android
Description
The Tip Calculator app shown in this figure is displayed in an emulator for Android
4.2 (API level 17).
If the Hardware Keyboard option is not enabled for an emulator, you can use the
on-screen keyboard, known as a soft keyboard, to enter text as shown in this figure.
If the Hardware Keyboard option is enabled for an emulator, you can use your
computers keyboard to enter text.
To calculate a tip, click the Bill Amount text box and enter the bill amount. When
youre done, press the Done key.
To increase or decrease the tip amount, click the Increase (+) or Decrease (-)
buttons.
The app automatically recalculates the tip and total amounts whenever the user
changes the bill amount or tip percent.
Figure 1-7
17
18
Section 1
Chapter 1
An introduction to Android
The activity_tip_calculator.xml
Page 1
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp" >
<!-- The bill amount -->
<TextView
android:id="@+id/billAmountLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="@string/bill_amount_label"
android:textSize="20sp"
android:textStyle="bold" />
<EditText
android:id="@+id/billAmountEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/billAmountLabel"
android:layout_marginLeft="5dp"
android:layout_toRightOf="@+id/billAmountLabel"
android:ems="8"
android:inputType="numberDecimal"
android:text="@string/bill_amount"
android:textSize="20sp" >
<requestFocus />
</EditText>
<!-- The tip percent -->
<TextView
android:id="@+id/percentLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/billAmountLabel"
android:layout_below="@+id/billAmountLabel"
android:padding="10dp"
android:text="@string/tip_percent_label"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/percentTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/percentLabel"
android:layout_alignLeft="@+id/billAmountEditText"
android:padding="5dp"
android:text="@string/tip_percent"
android:textSize="20sp" />
Figure 1-8
19
20
Section 1
The fifth attribute sets the text thats displayed on the widget to the value
thats stored in the bill_amount_label string of the strings.xml file, which youll
learn about in a moment. To get a string from the strings.xml file, the value for
this attribute begins with @string/. This indicates that the following text is the
name of the string element that contains the text.
To specify the size of the text, the textSize attribute specifies a measurement
of 20sp. Here, sp stands for scale-independent pixel. In general, its considered
a best practice to use scale-independent pixels for text sizes whenever possible
as it allows your text sizes to scale properly. Finally, the textStyle attribute sets
the style of this text to bold.
The EditText element that follows displays the widget that allows the
user to enter a bill amount. The Android documentation refers to this type of
widget as an editable text view, but you can also refer to it as a text box. Most
of the attributes of this EditText element work similarly to those of the previous TextView element. However, there are some differences. For example, the
alignment attributes align the text box relative to its label. Then, the ems attribute
specifies that the text box width should be 8 ems (8 of the letter m). Next, the
inputType element specifies that the soft keyboard should only allow the user to
enter decimal numbers.
To make it easy to test this app, the text attribute for the EditText element
specifies a default value of 34.60. During development, you can leave this
attribute set to a default value like this one. However, once the application is
working, you can set this attribute to an empty string.
The next two TextView elements define the widgets that display the tip
percent. By now, you should have a general idea of what most of the attributes
do. The main point to notice is that the layout attributes align these controls relative to one another. For example, the label for the tip percent is aligned with the
left side of the label for the bill amount. Similarly, the percent label is displayed
below the bill amount label.
The Button elements define the buttons that allow the user to increase or
decrease the tip percent. These widgets are 45dp wide and high and theyre
aligned to the right of the TextView widgets for the tip percent.
The last four TextView elements define the widgets that display the tip and
total amounts. These elements work like the previous TextView elements shown
in this figure.
Chapter 1
An introduction to Android
Figure 1-8
Page 2
21
22
Section 1
Chapter 1
An introduction to Android
Page 3
name="tip_percent_label">Percent</string>
name="tip_percent">15%</string>
name="increase">+</string>
name="decrease">-</string>
<string name="tip_amount_label">Tip</string>
<string name="tip_amount">$0.00</string>
<string name="total_amount_label">Total</string>
<string name="total_amount">$0.000</string>
</resources>
Description
In Android development, an activity is a screen that users can interact with.
The activity_tip_calculator.xml file contains the XML that defines the user
interface.
The strings.xml file contains the XML for the text strings that are displayed in the
user interface.
Figure 1-8
23
24
Section 1
Chapter 1
An introduction to Android
Page 1
package com.murach.tipcalculator;
import java.text.NumberFormat;
import
import
import
import
import
import
import
import
import
android.os.Bundle;
android.view.KeyEvent;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.EditText;
android.widget.TextView;
android.widget.TextView.OnEditorActionListener;
android.app.Activity;
Figure 1-9
25
26
Section 1
After displaying the user interface, the onCreate method gets references
to the six widgets that it declared earlier. To do that, it calls the findViewById
method for each widget and uses the R class to pass the ID of the widget to that
method. Then, it casts the widget object thats returned to the appropriate type.
These types correspond with the names of the elements in the XML file for the
user interface.
After getting references to the widgets, this code sets the listeners. First, it
sets the current class (TipCalculatorActivity) as the listener for the EditorAction
event on the bill amount text box. As a result, the onEditorAction method in this
class is executed when the user uses the bill amount text box to enter an amount
for the bill. Then, this code sets the current class as the listener for the Click
event on both of the buttons. As a result, the onClick method is executed when
the user clicks on either button.
After setting the listeners, this code calls the calculateAndDisplay method.
This method calculates the tip and total amounts and displays all current data on
the user interface. To start, it gets the string that was entered into the bill amount
text box. Then, it checks whether the string is empty. If so, it sets the bill amount
to zero. Otherwise, it converts the string to a float value. Next, it calculates the
tip and total amounts. Finally, it formats and displays the results of the
calculations. To do that, it uses the NumberFormat class to convert the float
values into string values that have currency and percent formatting.
The onEditorAction method is executed whenever the user presses an action
key on a soft keyboard such as the Done key. This method calls the
calculateAndDisplay method to calculate the new tip amount and total and
display it on the user interface.
The onClick method is executed whenever the user clicks on either of the
buttons. This method begins by using a switch statement to check which button
is clicked. Then, if the Decrease (-) button is clicked, this code decreases the tip
percent by 1 percent and calls the calculateAndDisplay method to refresh the
data thats on the user interface. Conversely, if the Increase (+) button is clicked,
this code increases the tip percent by 1 percent and calls the
calculateAndDisplay method to refresh the data.
Chapter 1
An introduction to Android
Page 2
Figure 1-9
27
28
Section 1
Chapter 1
An introduction to Android
Description
The Android manifest (the AndroidManifest.xml file) specifies some essential
information about an app that the Android system must have before it can run the
app, including the first activity to launch when the app is started.
Figure 1-10
29
30
Section 1
Perspective
The goal of this chapter has been to introduce you to some concepts and
terms that you should understand before getting started with Android programming. However, this chapter is just an overview of Android programming. In
the next few chapters, youll learn the hands-on skills you need to develop a
simple Android app like one shown in this chapter.
Terms
Android
application
app
Open Handset Alliance
Android Open Source Project (AOSP)
Software Development Kit (SDK)
Android stack
Dalvik virtual machine (VM)
Java virtual machine (JVM)
Integrated Development Environment
(IDE)
project
building
Java source code
Java bytecodes
Dalvik executable files
Android package
Android manifest
signed app
emulator
Chapter 1
An introduction to Android
Summary
Android is a Linux-based operating system designed primarily for touchscreen mobile devices such as smartphones and tablet computers. It was first
released in 2008. Android code is open-source.
Android developers write applications, or apps.
Android system architecture, known as the Android stack, consists of four
layers: Linux, native libraries, the application framework, and Android apps.
An Android app is typically developed using an IDE (Integrated
Development Environment) like Eclipse, using Java as the programming
language.
Android apps can be run on a physical Android device or on an emulator,
also called an Android Virtual Device (AVD).
An Android project must be built before it is run, compiling the Java source
code (.java files) into Java bytecodes (.class files) and then into Dalvik
executable files (.dex files).
All of the files for an Android project are put into an Android package (.apk
file), which includes a binary version of the AndroidManifest.xml file.
To run an app on an emulator or device, it must be digitally signed with a
certificate.
The Android debug bridge (ADB) lets your IDE communicate with an
emulator or a physical Android device.
31
Teach yourself how to develop and deploy professionalquality apps that work on a wide range of Android devices
and that are inviting and easy-to-navigate for users
Pick up new skills whenever you want to or need to by focusing on material thats
new to you
Look up coding details or refresh your memory on forgotten details when youre in
the middle of developing an Android app
Loan to your colleagues who are always asking you questions about Android
programming
100% Guarantee
You must be satisfied. Each book you buy directly
from us must outperform any competing book or
course youve ever tried, or send it back within 90
days for a full refundno questions asked.
Thanks for your interest in Murach books!