Android Development Tools for Eclipse
Set up, build, and publish Android projects quickly using Android Development Tools for Eclipse
Sanjay Shah
Khirulnizam Abd Rahman
BIRMINGHAM - MUMBAI
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2013 Production Reference: 1200713
Published by Packt Publishing Ltd.
Livery Place 35 Livery Street
Birmingham B3 2PB, UK..
ISBN 978-1-78216-110-3 www.packtpub.com
Credits
Authors Sanjay Shah
Khirulnizam Abd Rahman
Reviewer Thomas Iguchi
Acquisition Editor Wilson D'souza
Commissioning Editors Sharvari Tawde Ameya Sawant
Technical Editors Ruchita Bhansali Shashank Desai Larissa Pinto
Project Coordinator Amey Sawant
Proofreader Linda Morris
Indexer Rekha Nair
Production Coordinator Nilesh R. Mohite
Cover Work Nilesh R. Mohite
About the Authors
Sanjay Shah
has worked on diverse areas of application development across the mobile and web platform with more than 8 years of experience. He is currently working as a Software Architect and works in the area of Cloud Based Big Data Analytics combined with Distributed Cognition leveraging various Java-based technologies. He is fond of philosophy and enjoys life in Nepal, the land of the highest peak in the world, Mt. Everest.I would like to thank each and every one who knows me and supported me at different aspects of my life. Special thanks to my parents without whom I wouldn't be what I am today.
Khirulnizam Abd Rahman
is a Computer Science lecturer in the faculty of Information Science and Technology, Selangor International Islamic College, Malaysia. He has been teaching programming since the year 2000.He started publishing Android apps in the year 2010, and his apps among others are Malay Proverb Dictionary (Peribahasa) and m-Mathurat. Currently, he is working on the apps for Windows Phone Version 8. PHP, C#, and Java are also the programming languages that he is familiar with.
I would like to express my deepest gratitude to my beloved family;
Mahani, Luqman, Muna, and Amir for making my life more colorful.
Because of you, I am a grown up person with a heart full of love.
In fact, as long as they are happy, I will be happy. Other than programming, teaching, writing and being with my family, I don't
About the Reviewer
Thomas Iguchi
is the founder of Nobu Games LLC, a video games and mobile app development company, in La Crosse, Wisconsin. His latest Android game"Zoolicious" has gained international recognition and awards from various Android news and review websites such as AndroidTapp and Famigo.
Thomas has a wide repertoire of skills, which include programming, graphic designing, and music composition. His interest in computers and programming dates back to his childhood, when he became a self-taught programmer. He later went on to deepen his theoretical knowledge by studying Computer Science at the University of Mainz, Germany, with focus on linguistics, model-driven architecture, and software engineering. Overall he looks back at over 20 years of programming experience with professional expertise in web, mobile applications, and video game development. His consulting work for a mobile app development company, which serviced the financial industry, in Frankfurt, Germany, allowed him to perfect his professional Android programming skills.
For the last 12 years, Thomas has been self-employed working as a web designer, programmer and consultant, as well as video game graphic designer for the coin-op entertainment industry.
www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
TM
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print and bookmark content
• On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
Table of Contents
Preface 1 Chapter 1: Installing Eclipse, ADT, and SDK 5
Introducing the Android platform 6
What is Android? 6
Introducing the Android app 6
What is Dalvik Virtual? 7
Understanding API level 7
How many versions (distributions) Android has? 7
Preparing for Android development 9
Installing the JDK 10
Installing the Android SDK 11
Installing the Eclipse (Juno) 13
Installing the ADT in Eclipse Juno 15
Linking the Android SDK to the Eclipse 18 Summary 23
Chapter 2: Important Features of the IDE 25
Project explorer 26
Code editor 28
Graphical layout editor 29
Android manifest editor 30
Menu editor 30
Resources editor 30
XML resources editor 30
Graphical user interface designer 30
The configuration chooser 31
The screen layout designer 31
Properties window 32
Debugging pane 32
Dalvik Debug Monitor Server (DDMS) 34
SDK manager 35
Android virtual device manager 37
Running the Application 40
Getting help 40
Summary 40
Chapter 3: Creating a New Android Project 41
Creating a new Android application project 42String resources 46
Using the graphical layout designer 47
The XML layout code editor 50
Widget interactions through the source code editor 50
Toast message 54
Running the application on the emulator 55 Running the application on an Android device 56
Summary 57
Chapter 4: Incorporating Multimedia Elements 59
Adding a TableLayout 62
Adding the image resources 63
Adding ImageView 64
Adding ImageButtons 66
Assigning the widget's ID 67
ImageButtons and handling event 70
Adding audio 73
Adding another screen in the app 75
Adding HTML to WebView 77
Intent and Activity 78
The final product run and test 80
Summary 80
Chapter 5: Adding RadioButton, CheckBox, Menu,
and Preferences 81
Creating a new project 82
Adding a RadioGroup, RadioButton, and a TextField 83
Adding a CheckBox 84
Adding a menu 86
Defining the Strings 87
Defining the Preference screen 87
Hook up 90
Binding the menu and Preference 90
Getting values from Preferences 91
Table of Contents
[ iii ]
Run the application 94
Summary 95
Chapter 6: Handling Multiple Screen Types 97
Using wrap_content and match_parent 98
Fragment 98
Defining Fragment and Landscape layout 99
Hook up in the Main Layout file 102
Running the application 103
Optimizing for tablet 104
Persisting the state information during the state transition 105 Summary 106
Chapter 7: Adding an External Library 107
Creating an account at the AdMob website 107Adding Site/Application 108
Choosing the Ad Network Mediation 111
Adding AdMob SDK to the project 112
Making changes in the manifest file 113
Adding the AdMob widget/view in the layout file 114
Running the application 115
Summary 116
Chapter 8: Signing and Distributing APK 117
APK – Android package 117
Preparing for release 118
Compilation for release 118
Generating a private key 119
Signing 119 Alignment 119
Using the Eclipse ADT for release 119
Publishing to Google Play 122
Getting help 123
Summary 123
Index 125
Preface
Android Development Tools for Eclipse will show you how to use ADT (Android
Development Tools) for Eclipse to quickly set up Android projects, create application UI, debug and export a signed (or unsigned) .apk package for distribution using a hands-on practical approach. The book starts with the installation of ADT, discusses important tools and guides you through Android application development from scratch, demonstrating different concepts and implementation, and finally helps you distribute it.
What this book covers
Chapter 1, Installing Eclipse, ADT, and SDK, guides you through the installation of Eclipse and ADT(Android Development Tools) needed for Android
application development.
Chapter 2, Important Features of the IDE, describes several important features in Eclipse and an ADT Environment useful to develop native Android apps.
Chapter 3, Creating a New Android Project, guides you through the creation of a new project and demonstrates the usage of simple widgets. It also guides across compiling, debugging, and running the application.
Chapter 4, Incorporating Multimedia Elements, will teach you how to include multimedia elements and handle multiple screens in the application.
Chapter 5, Adding RadioButton, CheckBox, Menu, and Preferences, deals with adding menus and Preference Screen and the usage of radio button and check box.
Chapter 6, Handling Multiple Screen Types, teaches you how to tackle different screen types and orientations.
Chapter 7, Adding External Library, guides you through adding external library, that is, the AdMob library and incorporating advertisements in the application.
Chapter 8, Signing and Distributing APK, shows the steps involved in signing and distributing the Android application.
What you need for this book
It is advisable to have a laptop or a PC with the following specifications for better performance during development:
• 4 GB RAM
• Window 7 OS
• Dual Core /i-Series processor
Who this book is for
Android Development Tools for Eclipse is aimed at beginners and existing developers who want to learn more about Android development. It is assumed that you have experience in Java programming and you have used IDE for development.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"We can include other contexts through the use of the include directive."
A block of code is set as follows:
[default]
exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)
Preface
[ 3 ]
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default]
exten => s,1,Dial(Zap/1|30) exten => s,2,Voicemail(u100) exten => s,102,Voicemail(b100) exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
# cp /usr/src/asterisk-addons/configs/cdr_mysql.conf.sample /etc/asterisk/cdr_mysql.conf
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "clicking the Next button moves you to the next screen".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to [email protected], and mention the book title via the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book.
If you find any errata, please report them by visiting http://www.packtpub.com/
submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at [email protected] if you are having a problem with any aspect of the book, and we will do our best to address it.
Installing Eclipse, ADT, and SDK
This chapter serves as an installation instruction for all the development toolkits required to develop Android on Windows environment. It is separated into the following subtopics:
• Brief introduction to the Android platform
• Installing the Java Development Kit (JDK)
• Installing the Android SDK
• Installing the Eclipse (Juno)
• Installing the Android Development Toolkits (ADT) in Eclipse (Juno)
• Linking the Android SDK to the Eclipse
Before we proceed with the installation guide, there is some basic information an Android developer must know.
Introducing the Android platform
In simple terms, Android is a Linux based operating system for touch screen devices developed by Android Inc., financed by Google and was bought in later 2005. The beta version of Android came back in November 2007 and the commercial version 1.0 was released in September 2008. As of 2013, over 500 million active devices use the Android OS worldwide.
What is Android?
Android is a software stack for mobile devices that includes an operating system, middleware and key applications (platform). The Android Software Development Kit (SDK) provides the tools and Application Programming Interfaces (APIs) necessary to begin developing applications on the Android platform using the Java programming language. The kernel of Android is Linux.
Introducing the Android app
A mobile software application that runs on Android is an Android app. The apps use the extension of .apk as the installer file extension. There are several popular examples of mobile apps such as Foursquare, Angry Birds, Fruit Ninja, and so on.
Primarily in an Eclipse environment, we use Java, which is then compiled into Dalvik bytecode (not the ordinary Java bytecode). Android provides Dalvik virtual machine (DVM) inside Android (not Java virtual machine JVM). Dalvik VM does not ally with Java SE and Java ME libraries and is built on Apache Harmony java implementation.
Chapter 1
[ 7 ]
What is Dalvik Virtual?
Dalvik VM is a register-based architecture, authored by Dan Bornstein. It is being optimized for low memory requirements and the virtual machine was slimmed down to use less space and less power consumption.
Understanding API level
API level is an integer value that uniquely identifies the framework API revision offered by a version of the Android platform.
The Android platform provides a framework API that applications can use to interact with the underlying Android system. The framework API consists of:
• A core set of packages and classes
• A set of XML elements and attributes for declaring a manifest file
• A set of XML elements and attributes for declaring and accessing resources
• A set of Intents
• A set of permissions that applications can request, as well as permission enforcements included in the system
How many versions (distributions) Android has?
The latest distribution statistics until May 1, 2013, are shown in the following screenshot. It indicates that Android 2.3.3 has the largest market share; however, Android 4.1.x is gaining momentum and will have the dominant share. It is important to know that if the app is primarily targeted to an Android version, it will not run on the previous version of Android.
For instance, if you are developing an app for Android 2.2 (API level 8), then the application will not run on Android 2.1 (API level 7) and below. However, the app is compatible for Android 2.2 and later.
Pie chart of the Android API level distribution
(Source: http://developer.android.com/about/dashboards/index.html)
The Android API level distribution
(Source: http://developer.android.com/about/dashboards/index.html )
Chapter 1
[ 9 ]
Preparing for Android development
In this part of the chapter, we will see how to install the development environment for Android on the Eclipse Juno (4.2). Eclipse is the major IDE for Android
development (see the following screenshot). We need to install eclipse extension ADT (Android Development Toolkit) for development of the Android Application:
ADT on Eclipse in action
To download Android packages a Google API internet connection is a must, hence take this in notice before moving further. The steps on Windows using Eclipse Juno are as follows:
Software needed:
• Latest JDK1.6.x from Oracle
• Latest Android SDK
• Eclipse 4.2 (Juno)
Installing the JDK
To check whether your PC has an existing JDK and it is installed correctly, go to command prompt, and type javac –version (as shown in the following screenshot). It is recommended to install JDK 1.6.x for Android Application Development as it may complain that the compiler compliance level is greater than 6, and could run into problems:
Checking the JDK version
You may download JDK 1.6 (Java Development Toolkit) from the download site and install it. Make sure that JAVA_HOME is set after the installation, and check the version executing the preceding command.http://www.oracle.com/technetwork/
java/javase/downloads/index.html (see the following screenshot).
This step can be skipped if we have java 1.6.x installed:
Java PATH setting
Chapter 1
[ 11 ]
Installing the Android SDK
Create a folder named android-dev (android-dev is just a suggestion; you may create another name instead). The folder android-dev will be used consistently throughout this chapter. This folder is to hold all the software that is needed for Android development. This folder is needed again in another procedure.
Download from http://developer.android.com/sdk/index.html, and install this software in the android-dev folder. Bear in mind this download only provides the basic tools of Android SDK, not the complete installation. Later, we need to download the Android system images, APIs, examples, documentations and other libraries:
Android SDK download page
After completion of the download, install the SDK in the folder mentioned earlier; in C:\android-dev\android-sdk as shown in following screenshot.
During the installation, the Android SDK will detect the Java Development Kit in the machine. If we have installed the latest JDK, it should have no problems:
Android SDK installation path
Chapter 1
[ 13 ]
Installing the Eclipse (Juno)
Eclipse Juno (4.2) is available for download at http://www.eclipse.org/
downloads/:
Download page of Eclipse Classic
The Eclipse comes in a ZIP file, so just unzip it and find the eclipse.exe file to run it.
Immediately extract Eclipse in the folder as created earlier (in C:\android-dev).
After the extraction, create a desktop shortcut to make life easier, as depicted in the following screenshot:
Create Eclipse shortcut
Chapter 1
[ 15 ]
Installing the ADT in Eclipse Juno
Run Eclipse by identifying the Eclipse installation folder and double-click eclipse.exe (or double-click the shortcut in the Desktop). Provide a folder to store all the projects' source codes. And once again, create this folder under the android-dev folder, as shown in the following screenshot:
Select Eclipse Workspace
This new Eclipse installation does not provide the Android Developer Toolkits (ADT) plugins. To install this plugin navigate to Window | Preferences to open the Preferences panel. Click on Install/Update | Available Software Sites (on the left panel). Click on the Add button (on the right panel) to add a software download site (again an Internet connection is needed).
Another window will appear. Provide ADT in the Name (for example), and the Location https://dl-ssl.google.com/android/eclipse/(as provided in http://developer.android.com/sdk/eclipse-adt.html):
In the Available Software dialog, select the checkbox next to Developer Tools and click on Next. In the next window, you'll see a list of the tools to be downloaded.
Select all except NDK plugins and click on Next. We will be discussing the tools in the next chapters:
Chapter 1
[ 17 ]
Selecting the ADT and SDK tools
Read and accept the license agreements, then click on Finish. If you get a security warning saying that the authenticity or validity of the software can't be established, click on OK. When the installation completes, restart Eclipse.
Linking the Android SDK to the Eclipse
Run Eclipse. In the Windows | Preferences, click on Android. Locate the folder of the android-sdk from the step where you installed the android-sdk, as shown in the following screenshot:
Android preferences in Eclipse
Click on Apply and hit OK.
Chapter 1
[ 19 ]
The next thing to do is to download the Android APIs and the operating system images. Installing Android SDK is time consuming. It requires a smooth broadband line because after the installation you need to download the API package for Android and Google API.
To start this, click on the Android SDK Manager icon, as shown in the following screenshot:
The Android SDK Manager icon
You will be provided with the list of all SDK Platforms for all Android versions.
I suggest you be selective, just download your target platform first. If you are to develop an app for Froyo (Android 2.2) you need to download the API version 8.
Later, when you have more time, you could come back and download for the other version. If you do not have any time and Internet data constraints then you may download all. It will fetch API packages, Android OS images, debugging tools and other softwares related to Android development.
For this time, we will download the latest SDK with Jellybean system image and API level 16, as shown in the following screenshot:
Installing SDK with API level 16
Chapter 1
[ 21 ]
Before hitting the Install button, there is one important tip I'd like to share. While conducting this procedure, we may encounter a connection reset problem for no specific reason. To get over this issue, on the Android SDK Manager window, navigate to Tools | Options. Uncheck the Force https://...sources to be fetched using https://... option, and Close (shown in the following screenshot). You may start the SDK and API installation now:
After the SDK, APIs and system images have been downloaded, restart Eclipse. The wait is worth it! After almost a couple of hours of installation and downloading packages, I got this nice graphical interface for the screen layout arrangement, as shown in the following screenshot. Check the Android Preferences window, and you may see the Android 4.1 in the API list. To add another API, again you need to download through the Android SDK Manager:
List of Android APIs
To avoid earlier steps on setting up ADT with Eclipse and kick start development please download the ADT bundle from http://developer.android.com/sdk/
index.html and follow the steps for setting up at http://developer.android.
com/sdk/installing/bundle.html.
In the next chapter, we will look into tools of an ADT environment that eases the development.
Chapter 1
[ 23 ]
Summary
In this chapter, we learnt how to install the Eclipse Juno (the IDE), the Android SDK and the testing platform. The next chapter will discuss the important elements of the IDE before we create a new Android Application project.
Important Features of the IDE
This chapter describes several important features in Eclipse and an ADT Environment useful to develop an Android app. It is separated into the following topics:
• Project explorer
• Code editor
• Graphical user interface designer
• Properties window
• Debugging pane
• Dalvik Debug Monitor Server (DDMS)
• SDK manager
• Android virtual device manager
• Running an application
• Getting help
Project explorer
The project explorer is a tool to view all folders and files under a project. By
double-clicking the item, one can open and edit the file. When we create a new project, which will be discussed thoroughly in Chapter 3,Creating a New Project, the ADT will automatically create all these default folders and files, as shown in the following screenshot. Depending on the project, we may ignore or modify all these files.
These are brief descriptions of the default folders and files in your Android project:
Project explorer
Chapter 2
[ 27 ]
The table that follows contains the brief description of the important folders and files available in the project tree:
Folder Functions
/src the Java codes are here
/gen generated automatically
/assets put your fonts, videos, sounds here. Is more like a file system and can also place css, javascript files and so on.
/libs external library (normally in JAR) /res images, layout, and global variables
/drawable-xhdpi for extra high specification devices (for examples Tablet, Galaxy SIII, HTC One X)
/drawable-hdpi for high specification phones (Examples: SGSI, SGSII) /drawable-mdpi for medium specification phones (Examples: Galaxy W,
HTC Desire)
/drawable-ldpi for low specification phones (Examples: Galaxy Y, HTC WildFire )
/layout all XML files for the screen(s) layout /menu XML files for the screen menu
/values global constants
/values-v11 template style definitions for devices with Honeycomb (Android API level 11)
/values-v14 template style definitions for devices with ICS (Android API level 14)
AndroidManifest.xml One of the important files to define the apps. This is the first file located by the Android OS in order to run the app. It contains the app's properties, activity declarations and list of permissions.
Code editor
This is the tool where the programming is cooked. Several important features of the Eclipse code editor (programmers love to have) are intelligence and the error marker (refer screenshot to follow). Code completion suggests objects, methods or variables available to be incorporated in our code, while the error marker will notify any syntax error immediately without having to compile the code. These features help a lot for faster programming:
The code editor
The code editor's appearance is customizable to suit your style and preference.
To change the editor's environment, such as the background color or the code's font styles, right-click on the editor and choose Preferences, and then navigate to General | Appearance | Colors and Fonts. Then click on Edit to customize, refer the following screenshot:
Chapter 2
[ 29 ]
Customizing the Code Editor's appearance
There are also several other XML code editors that help during design and development. They come in two flavors: GUI based; where things can be
manipulated with a GUI interface, useful for someone who is uncomfortable editing the XML code manually; Source based: where XML codes can be manually edited.
Some of the editors are listed as follows:
Graphical layout editor
Edit and design your XML layout files with a drag and drop interface.
The layout editor renders your interface as well, offering you a preview as you design your layouts.
Android manifest editor
Edit Android manifests with a simple graphical interface. This editor is invoked when you open an AndroidManifest.xml file.
Menu editor
Edit menu groups and items with a simple graphical interface. This editor is invoked when you open an XML file with a <menu> declared (usually located in the res/menu folder).
Resources editor
Edit resources with a simple graphical interface. This editor is invoked when you open an XML file with a <resources> tag declared.
XML resources editor
Edit XML resources with a simple graphical interface. This editor is invoked when you open an XML file.
Graphical user interface designer
This is the interface designer. It functions as the GUI editor for controls or a widget to the application screen. There are three sections of this GUI designer, the palette, configuration chooser and the screen layout preview, as shown in the following screenshot:
Chapter 2
[ 31 ]
The ADT's GUI designer
The Palette contains all the GUI controls (widgets) that can help us design the interface. The available controls depend upon the API level we choose during creation of the project. Some of the common controls are: button, text field, radio button, check box, multimedia controls and so on.
The configuration chooser
It lets you decide the appearance of your app view across different screen sizes, orientation, densities and themes.
The screen layout designer
It is a canvas to put things up and try out different designs. It is a designing workspace. Also, it provides a preview of how the screen may appear in a device.
Properties window
It helps in editing properties of the widgets. All the properties corresponding to widgets can be viewed and edited via this window visually. Though the properties can be edited directly by editing the XML file, this GUI interface eases it. All the changes made are persisted to XML file instantly and automatically. The following screenshot shows the Properties window:
The Properties window
Debugging pane
In the debugging perspective, we see the syntax errors, warning, console messages, run-time errors, variable transition (if breakpoint is used) and LogCat. LogCat is useful to trace any activity happening inside the device or emulator. The following screenshot shows the window to list all code problems, such as warnings or syntax errors:
Chapter 2
[ 33 ]
Problems warnings or code syntax errors
A sample of console messages from the ADB is listed in the following screenshot.
As a java person, we would be tempted to use System.out.println() to split out message and objects' values; which are shown in the LogCat view, however it is advisable to use Log class for this purpose, reason being we can filter, print different colors and define log types. This could be one way of debugging your program, by displaying variables' values or parameters. To use Log, import android.util.Log, and use one of the following methods to print messages to LogCat:
v(String, String) (verbose) d(String, String) (debug) i(String, String) (information) w(String, String) (warning) e(String, String) (error)
The Android Debug Bridge console (displays ADB activities)
LogCat is used to view the internal log of the Android system, as shown in the following screenshot. It is useful to trace any activity happening inside the device or emulator through the ADB (Android Debug Bridge). ADB is a tool to connect your PC with the virtual device or actual device. Without it, the developer cannot directly transmit the APK file to an Android device/emulator:
The LogCat (tracedump of all device/emulator activities)
Dalvik Debug Monitor Server (DDMS)
DDMS is a must have tool to view the emulator/device activities. To access DDMS in the Eclipse, navigate to Windows | Open Perspective | Other and then choose DDMS. By default it is available in the Android SDK (it's inside the folder android-sdk/tools by the file ddms). From this perspective the following aspects are available:
• Devices: The list of the devices and AVDs that are connected to ADB
• Emulator Control: It helps to carry out device functions
• LogCat: It views real time system log messages
• Threads: It gives an idea of currently running threads within a VM
• Heap: It shows heap usage by application
• Allocation Tracker: It provides information on memory allocation of objects
• File Explorer: It explores the device file system
Chapter 2
[ 35 ]
The following image shows important aspects of DDMS:
Dalvik Debug Monitor Server (DDMS)
SDK manager
SDK Manager is the tool to update Android SDK and manage the download of Android OS system images, documentations, and APIs. The icon appears, as shown in the following screenshot:
The SDK manager icon
The next screen to follow, as shown in the screenshot has a very long list. We need to be very decisive about what API level we need and select accordingly as the download may take significant time, depending upon the Internet speed. If not sure then choose the latest API level.
Expand the API level we want to issue and check the SDK platform. This download consists of the API for the corresponding level and the Android OS system image.
By default, the system image is based on the ARM's architecture. However to run Android OS system image faster on an Intel architecture machine, just tick the Intel Atom x86 System Image option.
Tick the Samples for SDK if you need to learn from the samples. If your app needs to incorporate the Google special API (such as the Google Maps), then you might need to download the Google API. The rest of the list is about the device specific APIs. Unless you are planning to optimize your app for a certain device, then do not download.
Once you have finished selecting the necessary APIs, then click on the Install
package button. Should you have any connection reset problem while downloading, navigate to Tools | Options. Uncheck the Force https://... sources to be fetched using http://... and try again:
The Android SDK Manager window
Chapter 2
[ 37 ]
Android virtual device manager
Android virtual device is a virtual mobile device (emulator) that runs on your computer. The emulator lets you test an Android application without using a physical device. Although, it's not the best testing approach, as it just mimics the device, but at least you have something to test in case you cannot afford an actual Android device.
When the emulator is running, you can interact with the emulated mobile device just as you would in an actual mobile device, except that you use your mouse pointer to touch the touchscreen and you are able to use some keyboard keys to invoke certain keys on the device.
The Android emulator mimics all of the hardware and software features of a typical mobile device, except that it cannot place actual phone calls. It provides a variety of navigation and control keys, which you can "tap" using your mouse or keyboard to generate events for your application. It also provides a screen in which your application is displayed, together with any other running Android applications.
For some features we may have to be aware of hot keys and details are at http://developer.android.com/tools/help/emulator.html#KeyMapping Click on the button as shown in the following screenshot, to open the Android SDK and AVD Manager window. AVD is Android Virtual Device:
The AVD icon
The AVD Manager is shown in the following screenshot. First, click on New… to set a new emulator, as seen in the screenshot. Enter a name (for example, nexus), choose a target (make sure the Android OS system image has been downloaded for the selected target), and for simplicity choose the device, and all other fields will be auto-populated. We can also edit if you want something different. Also, choose CPU as ARM (armeabi-v7a) and click on Create AVD:
Creating a new AVD
Chapter 2
[ 39 ]
Click on the new AVD that is already created, and start the AVD using the Start button. Use the default setting and click on the Launch button.
If we have a lower specification of processor and memory, you will notice that its emulator boot-up is really slow. I would like to advise you to have at least 3GB of RAM to make it faster.
Wait until the left screen displays a nice picture with icons, as shown in the following screenshot. The left component is your device (smartphone) screen and the right component is the physical smartphone keypad:
The Android emulator
Running the Application
The project with no error will be able to be executed and sent to the AVD. To run a project, click on the Run button as, shown on the following image. If your system is already running several emulators, Eclipse will ask which version of the emulator to use:
The Run application button
Getting help
• Go to Help in the menu, and choose Search
• Eclipse help: http://help.eclipse.org/juno/index.jsp
• ADT help: http://developer.android.com/tools/help/adt.html
• Android developer's official reference: http://developer.android.com
• ADT update: regularly check the ADT update from the menu, Help | Check for Updates
• More on DDMS: http://developer.android.com/tools/debugging/
ddms.html
Summary
In this chapter, we discussed several important tools available in the Eclipse and the ADT, such as the project explorer, code editor, graphical user interface designer, properties window, debugging pane, Dalvik debug monitor, SDK manager, AVD manager, and the run application facilities. The next chapter will discuss how to create a new Android application project.
Creating a New Android Project
This chapter will demonstrate how to create a new Android app with a simple interaction using the button and text field. We will also write interactivity code, compile and run an app on the emulator/actual device. To illustrate this chapter, we will be creating a simple project named HelloU app.
• Creating new Android application project string resources
• Using the graphical layout designer
• String resources
• The XML layout editor
• Widgets' interactions through the source code editor
• Toast message
• Running the application on the emulator
• Running the application on an Android device
• Getting help
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.
packtpub.com/support and register to have the files e-mailed directly to you.
Creating a new Android application project
To create a new Android project in the Eclipse, navigate to File | New | Project.
A new project window will appear, then choose Android | Android Application Project from the list. Click on the Next button.
• Application Name: This is the name of your application, it will appear side-by-side to the launcher icon. Choose a project name that is relevant to your application.
• Project Name: This is typically similar to your application name. Avoid having the same name with existing projects in Eclipse, it is not permitted.
• Package Name: This is the package name of the application. It will act as an ID in the Google Play app store if we wish to publish. Typically it will be the reverse of your domain name if we have one (since this is unique) followed by the application name, and a valid Java package name, else we can have anything now and refactor it before publishing.
The android:minSdkVersion is an integer designating the minimum API Level required for the application to run. If not sure, leave it to whatever is selected.
For example, you might have your app set to android:minSdkVersion="7". This setting will guarantee that your app works on devices with Android Éclair (2.1) or above, but not below.
The targetSdkVersion is the target devices you are focusing on. Let's say your app has android:minSdkVersion="16", it means the apps could utilize all the features of Android Jelly Bean. However, bear in mind that features, such as the ability to move the app to an SD card and native Unicode are not supported in Android (2.1) Eclair.
Though these features are available starting in the API level 8 (Android 2.2/Froyo) and level 11 (Android 3.0/Honeycomb), they cannot be utilized in the lower version of Android.
Chapter 3
[ 43 ]
Do keep in mind that your targetSdkVersion has to be equal or more than the minSdkVersion. Otherwise, it doesn't really make much sense.
Click on Next to move to the next step:
Create a new Android project
This is the window to configure your launcher icon. The launcher icon is the icon that will appear in the home screen or in the application drawer. This is an important aspect of your app as it will be representing the app. For this purpose, you may use the icon creator wizard using the available text and icon shape pre-customized in the ADT. Set the foreground as text, provide the letter U as the Text, pick the circle as the icon shape and adjust your color preference, as shown in the following screenshot. This wizard will create a simple icon and provides the ldpi (36x36 pixels), mdpi (48x48 pixels), hdpi (72x72 pixels) and xhdpi (96x96 pixels) of the launcher icon. Icons of different sizes are created to address various devices with different configuration of screen sizes and resolution. Click on Next to proceed:
Launcher icon creator
Choose BlankActivity in the window, as shown in following screenshot, and click on Next:
Chapter 3
[ 45 ] Choose blank activity
The next window appears to input the MainActivity name, as shown in the following screenshot and click on the Finish button:
String resources
Usually, it is a practice for Android application to store the string values for user interface reference in the XML file due to the nature of mobile apps, which is distributed internationally. So it is best to provide multiple language options.
However, this practice is optional, and you may use direct string assigning if you wish to do so.
The string resource file is in an XML form and available through the project tree in res/values/strings.xml. These string resources can also be used to store color information, integer arrays to name some.
Now, add a new string value by clicking on the Add button, provide the variable name in the Name box and the Value of the string. Press Ctrl + S to save the changes.
For example, in the following screenshot, a new string variable is created as hello_u and the value is Hello,:
Adding a new string value
Add two more string values based on the table that follows. These strings will be used as the widgets' caption:
String variable Value s_tvName Your name:
s_btnDisplay Display name!
Chapter 3
[ 47 ]
If you notice, we use s_ to indicate it is a string variable from the resources, tv to indicate a TextView, and btn to indicate a button. Bear in mind that these conventions are not fixed, you may use your own preferences.
The new string values created will be saved in the string.xml file. The XML code is available by clicking on the tab on the red arrow, as shown in the following screenshot:
The string.xml code file
Using the graphical layout designer
The next exercise is to add a text label, a text box and a button. These elements are called widgets in Android which has the class name TextView, EditText and Button in the Android API. We will not go through the details of these classes; most importantly we could apply these widgets in our app.
To open this layout, double-click the res/layout/activity_main.xml file from the project explorer.
On the left of the app screen, you'll see the Palette. Browse the Form Widgets, there are several widgets including the TextView. Click and drag the TextView widgets to the app screen. Change the widget ID into "@+id/tvName", and make sure to press Enter to confirm your changes and save them to the XML file. The "@+id/" is the ADT representation to say that the new ID has to be created and assigned to the widget.
After that, set the Text properties to point the value defined in the string resources, s_tvName. This could be done by clicking on the button with three dots, on the right side of each property. Press Ctrl + S to save the changes and to make sure the changes appear in the XML file:
Changing the caption of a TextView
Chapter 3
[ 49 ]
The next widget to add is the EditText with Id txtName, associate label as Your name: to accept user input, as shown in the following screenshot:
Adding an EditText
Add another widget, button, specify ID btnDisplay and associate label as D isplay Name, as shown, and expand it horizontally across the screen. You may use the resize feature by clicking and dragging the bluish resize mark on the edge of the widget:
Adding a Button
The XML layout code editor
The code editor is an alternative to change the layout properties. We recommend you change this code directly if you have prior knowledge of XML. It's a straight forward XML code actually. To access this code directly, just click the activity_main.xml on the bottom of the layout editor, as shown in following screenshot:
Accessing the XML layout code editor
Widget interactions through the source code editor
The layout we designed previously does not have to interact with each other automatically; let's make it happen. To put in simple words, when we execute the project, clicking on the button on the app will not trigger any action. We need to add the code for the interactions.
What we are trying to do is when the user taps on the button Display Name!, the app will capture any text inside the TextView and produce a simple popup to display your name.
To achieve our goal let's play around, go to src, double click on the package folder and double click again on the file MainActivity.java. This Java file will contain the code to load the layout of the XML file main_activity.xml in order to create a UI.
The Java code as follows is the default code provided by ADT.
Chapter 3
[ 51 ]
You will see the package name on line one and several classes imported to the project. The code in line six is the main class declaration which inherits the Activity class. method onCreate in line eight is the first method to be called when the apps start. The setContentView(R.layout.activity_main) is the command to initialize the screen layout based on the main screen designed previously. And the method in line 13, which is to create the screen menu, will be discussed later in Chapter 5, Adding RadioButton, Checkbox, Menu, and Preferences.
package net.kerul.HelloU;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity{
//First method called when App starts @Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// loads Screen menu @Override
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
} }
In order to provide button interaction, we need to add implements OnClickListener to the main class header.
public class MainActivity extends Activity implements OnClickListener {
In the import section of the code, add this line:
import android.view.View.OnClickListener;
Now, initialize all the widgets that will get involved in the process. Immediately after the main class header, add the widgets' member declaration.
public class MainActivity extends Activity implements OnClickListener{
private EditText txtName;
private Button btnDisplay;
…
Since EditText and Button are also another class which needs to be imported from the Android API, so add a couple of lines in the import section.
import android.widget.Button;
import android.widget.EditText;
In Eclipse you do not need to memorize all the classes and the packages' names that are needed to be imported. Just put the cursor (caret) to the class and press Ctrl + Shift + O. The IDE will help you to include the packages involved or point your mouse to the additional class, a menu will come out, and choose to import the class.
Menu to import class from the Android API
Next is to link the code and the layout design in the MainActivity.xml file. This is needed since the ADT is incorporating the MVC (Model-View-Controller) development method. It means that the screen layout is separated from the code to provide high project maintainability.
Basically after the layout has been loaded using setContentView you need to have access to these widgets that hide within that layout. This is where findViewById () comes into play.
txtName=(EditText)findViewById(R.id.txtName);
btnDisplay=(Button)findViewById(R.id.btnDisplay);
Chapter 3
[ 53 ]
The button is the action; we need to add the event listener to the button. The line to add is as follow:
btnDisplay.setOnClickListener(this);
Here we made the Activity itself implement onClickListener.
For any on-click event to be handled, Java needs a special method to be included.
Inside the method is where the task will be executed. In our case, if the user clicks (or taps) the button (btnDisplay), the app will extract the content of the text field (txtName) and display the content on the screen. The action can be coded as follows:
public void onClick(View arg0) { if(arg0.getId()==R.id.btnDisplay){
String hellomsg="Hello, "+txtName.getText().toString();
Toast.makeText(this.getApplicationContext(), hellomsg, Toast.LENGTH_SHORT).show();
} }
View arg0 is the element that triggers the action. arg0.getId() is the method to get the ID of the widget triggering the action. If the widget ID is the btnDisplay, then do the action of capturing the input and display it to the screen.
To fetch the string of text field widgets, use the following code:
txtName.getText().toString();
Toast.makeText() is the method to display a short/brief message on the screen, we will discuss it in the next section.
The complete code would be:
package net.kerul.HelloU;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private EditText txtName;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName=(EditText)findViewById(R.id.txtName);
btnDisplay=(Button)findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(this);
}
public void onClick(View arg0) { if(arg0.getId()==R.id.btnDisplay){
String hellomsg="Hello, "+txtName.getText().toString();
Toast.makeText(this.getApplicationContext(), hellomsg, Toast.LENGTH_SHORT).show();
} } }
Toast message
This is one of the common practices to pop-up a message box for notifying the user.
This kind of notification is a type of notification that does not require a user answer or feedback.
Toast.makeText(this.getApplicationContext(), hellomsg, Toast.LENGTH_SHORT).show();
Toast.makeText() contains three parameters which are the application context, the message and the time length.
• The application context is the current screen to display the message
• The message is the string to be displayed
• The time length is consisting of a short or longer duration of the message display and has to be one of Toast.LENGTH_* constants
Chapter 3
[ 55 ]
The arrow in the following screenshot is pointing to a Toast:
Example of a Toast
Running the application on the emulator
Running the HelloU app in the emulator would need you to start the emulator first.
Start the emulator that has the Android version that suits your target platform. Once the emulator is fully loaded, we can compile and run the app.
Click on the HelloU project on the project explorer (this is to activate the project).
Navigate to Run in the Eclipse menu, and choose Run or press Ctrl + F11 for a shortcut. Select run as Android Application, and Enter. Wait for a couple of seconds and view your emulator. The HelloU app will appear shortly, as in shown in the following screenshot. Enter your name and tap on the Display Name! button, the Toast message will appear with the name entered on the bottom of the screen:
The HelloU app running in the Emulator
Running the application on an Android device
To run and deploy on a real device, first install the driver of the device. This varies as per device model and manufacturer.
These are some links you could refer:
• For Google Android devices only http://developer.android.com/sdk/
win-usb.html.
• Others: http://www.teamandroid.com/download-android-usb-drivers/. Make sure the Android phone is connected to the computer through the USB cable.
To check whether the phone is properly connected to your PC and in debug mode, please switch to the DDMS perspective.
The Android phone as appear in the DDMS.
If everything goes well, then run the app. Notice that a window appears asking you to select between the emulator and a real Android device; select the Android device.
A few seconds later, the app will be running in the Android phone.
Chapter 3
[ 57 ]
HelloU app in the actual Android device. Getting help
The following are some references to guide you on using the Eclipse and ADT. You can spend some time going through the documentation and tutorial to get updated.
Reading the tutorials and discussions at stackoverflow.com are among the convenient way of learning these tools.
• Go to Help in the menu, and choose Search.
• Eclipse help: http://help.eclipse.org/juno/index.jsp
• ADT help: http://developer.android.com/tools/help/adt.html
• Android Developer's official reference: http://developer.android.com
• ADT Update: regularly check the ADT update from the menu, Help | Check for Updates.
• More on DDMS: http://developer.android.com/tools/debugging/
ddms.html
Summary
Congratulations! You now have an Android app of your own. You have designed the screen layout, added a label, text field and a button. The simple interactivity exposed you to how to develop an android mobile app. In the next chapter, we will add more widgets and learn to develop more complex apps involving multiple screens.
Incorporating Multimedia Elements
This chapter will discuss how to incorporate multimedia elements inside a project and handle several screens in an app. The readers will be shown how to add images, sounds and an HTML page in the project. We will discuss the following topics with the help of a project called SimpleNumb3r5:
• Forming the layout
• Adding the image resources
• Inserting ImageView
• Inserting ImageButtons
• ImageButton and handling events
• Adding audio and multiple screen support
• Inserting HTML in a WebView
• Using Intent and Activity
• Adding a new activity in the manifest file
• The final product – run, deploy, and test app
For this chapter, we need a new project that will cover the Android devices from Version 2.1 (API level 7) to the latest version. So set android:minSdkVersion to 7, and android:targetSdkVersion to 16.
The icon and other resources are available in a downloadable source code (refer to the download tip mentioned in the Preface of this book). Download these materials prior to developing this app. We do not want to make your life miserable doing the graphic design.
The selected name for the new app is SimpleNumb3r5, as shown in the following screenshot. If you are wondering why we chose Android 2.1, this is to widen the device coverage:
Create a new Android project named SimpleNumb3r5
We provide the launcher icon in the resource materials and the image named ic_launcher-web.png in the Image File field, as shown in the following screenshot.
This is the dedicated logo of this app. Should you prefer a different logo to suit your app, you are welcome to design it personally. By using this wizard, the icon launcher will be prepared to suit the xhdpi, hdpi, mdpi, and ldpi formats in the respective drawable folder.
Chapter 4
[ 61 ]
Creating the launcher icon
The next screen, as shown in the following screenshot, is to provide a name of the application. This can be any string that has the right meaning suitable to the app.
The layout name will be created automatically for you, and could be changed to your preference. Choose the navigation type as None as it has no concern with respect to our application development.
Choose the blank activity