Chapter 1. Introduction to Android

Android is Google’s open source and free Java-based platform for mobile development. It enables developers to build real-world mobile applications using the Android software development kit (SDK) and publish them to the Android market. Android comes with several application programming interfaces (APIs) that make the task of developing full-featured applications easy. You can even use a camera, accelerometer, or GPS in an Android application. Moreover, Android is cross-compatible—it can run on Android phone/tablet/devices of different screen sizes and resolutions. Using Android, you can develop applications for a wide variety of devices, including phones, e-book readers, netbooks, and GPS units. Android was initially developed by Android, Inc., a small Palo Alto, California, company. Google bought this company in July 2005 and released the Android SDK in November 2007. Periodically, Google releases Android SDK updates. At the time of this writing, the latest version is 4.1.


Note

Android offers support for Bluetooth, EDGE, 3G, WiFi, Camera, GPS, compass, and accelerometer.


The Android 4.1 Jelly Bean SDK

The Android 4.1 Jelly Bean SDK was released with new features for developers in July 2012. It improves the beauty and simplicity of Android 4.0 and is a major platform release that adds a variety of new features for users and app developers. A few of the big features of this release include the following:

Project Butter—Makes the Jelly Bean UI faster and more responsive. Also CPU Touch Responsiveness is added, which increases CPU performance whenever the screen is touched. It uses the finger’s speed and direction to predict where it will be located after some milliseconds, hence making the navigation faster.

Faster speech recognition—Speech recognition is now faster and doesn’t require any network to convert voice into text. That is, users can dictate to the device without an Internet connection.

Improved notification system—Besides text, the notifications include pictures and lists too. Notifications can be expanded or collapsed through a variety of gestures, and users can block notifications if desired. The notifications also include action buttons that enable users to call directly from the notification menu rather replying to email.

Supports new languages—Jelly Bean includes support for several languages including Arabic, Hebrew, Hindi, and Thai. It also supports bidirectional text.

Predictive keyboard—On the basis of the current context, the next word of the message is automatically predicted.

Auto-arranging Home screen—Icons and widgets automatically resize and realign as per the existing space.

Helpful for visually impaired users—The Gesture Mode combined with voice helps visually impaired users to easily navigate the user interface.

Improved Camera app—The Jelly Bean Camera app includes a new review mode of the captured photos. Users can swipe in from the right of the screen to quickly view the captured photos. Also, users can pinch to switch to a new film strip view, where they can swipe to delete photos.

Better communication in Jelly Bean—Two devices can communicate with Near Field Communication (NFC); that is, two NFC-enabled Android devices can be tapped to share data. Also, Android devices can be paired to Bluetooth devices that support the Simple Secure Pairing standard by just tapping them together.

Improved Google Voice search—Jelly Bean is equipped with a question and answer search method that helps in solving users’ queries similar to Apple’s popular Siri.

Face Unlock—Unlocks the device when the user looks at it. It also prevents the screen from blacking out. Optionally “blink” can be used to confirm that a live person is unlocking the device instead of a photo.

Google Now—Provides users “just the right information at just the right time.” It displays cards to show desired information automatically. For example, the Places card displays nearby restaurants and shops while moving; the Transit card displays information on the next train or bus when the user is near a bus stop or railway station; the Sports card displays live scores or upcoming game events; the Weather card displays the weather conditions at a user’s current location, and so on.

Google Play Widgets—Provides quick and easy access to movies, games, magazines, and other media on the device. It also suggests new purchases on Google Play.

Faster Google Search—Google Search can be opened quickly, from the lock screen and from the system bar by swiping up and also by tapping a hardware search key if it is available on the device.

Supports antipiracy—This feature supports developers in the sense that the applications are encrypted with a device-specific key making it difficult to copy and upload them to the Internet.

Understanding the Android Software Stack

The Android software stack consists of a Linux kernel and a collection of C/C++ libraries that are exposed through an application framework for application development.

The Android software stack consists of four main layers, as shown in Figure 1.1.

Image

Figure 1.1. Android software stack

The following list gives a brief description of each of the layers in the software stack:

Linux kernel—The kernel on which Android is based contains device drivers for various hardware components of an Android device, including Display, Camera, Keypad, Wi-Fi, Flash Memory, and Audio.

Libraries—The next layer on top of the Linux kernel is the libraries that implement different Android features. A few of these libraries are listed here:

WebKit library—Responsible for browser support.

FreeType library—Responsible for font support.

SQLite library—Provides database support.

Media libraries—Responsible for recording and playback of audio and video formats.

Surface Manager library—Provides graphics libraries that include SGL and OpenGL for 2D and 3D graphics support.

Android runtime—The engine at the same layer as the libraries. It provides a set of core Android libraries and a Dalvik virtual machine that enable developers to write Android applications using Java. The core Android libraries provide most of the functionality available in the core Java libraries, as well as the Android-specific libraries. Dalvik VM is explained in detail later in this chapter.

Application framework—Provides the classes that enable application developers to develop Android applications. It manages the user interface, application resources, and abstraction for hardware access.

Application layer—Displays the application developed and downloaded by users, along with the built-in applications provided with the Android device itself.

Installing the Android SDK

For developing native Android applications that you can publish on the Google Play marketplace, you need to install the following four applications:

The Java Development Kit (JDK) can be downloaded from http://oracle.com/technetwork/java/javase/downloads/index.html.

The Eclipse IDE can be downloaded from http://www.eclipse.org/downloads/.

The Android Platform SDK Starter Package can be download from http://developer.android.com/sdk/index.html.

The Android Development Tools (ADT) Plug-in can be downloaded from http://developer.android.com/sdk/eclipse-adt.html. The plug-in contains project templates and Eclipse tools that help in creating and managing Android projects.

The Android SDK is not a full development environment and includes only the core SDK Tools, which are used to download the rest of the SDK components. This means that after installing the Android SDK Tools, you need to install Android platform tools and the other components required for developing Android applications. Go to http://developer.android.com/sdk/index.html and download the package by selecting the link for your operating system. For Windows users, the provided .exe file is named installer_r18-windows.exe. After downloading the file, double-click it to initiate the installation process. The Android SDK Manager window opens. The dialog boxes that you see from now on are from the Windows installer, and the screens may vary from other operating systems’ installers.

The first screen is a Welcome screen. Select the Next button to move to the next screen. Because the Android SDK requires the Java SE Development Kit for its operation, it checks for the presence of JDK on your computer. If JDK is already installed, you see the screen shown later in Figure 1.4. If the JDK is not found, it displays a button with the caption Visit java.oracle.com, which you can use to download and install JDK. On selecting the button, you are taken to http://www.oracle.com/technetwork/java/javase/downloads/index.html. This site shows links to download Java Platform, Standard Edition, Java SE Development Kit (JDK) bundles, and additional resources. The latest version of Java available at the time of this writing is JDK version 1.7. Select the JDK link that suits your platform (Windows, Linux, or Mac) and double-click the downloaded file to begin JDK installation. You will probably see a Security Warning dialog box, asking whether you want to run or cancel the execution of the file. Select the Run button to initiate JDK installation. The first screen that you see is a Java Setup Wizard Welcome screen. Select the Next button to see the Custom Setup dialog box for selecting optional JDK features that you want to install, as shown in Figure 1.2.

Image

Figure 1.2. The Custom Setup dialog box

Three categories of features (Development Tools, Source Code, and Public JRE) are displayed, and you can select from the respective drop-down lists to choose the list of features in the category you want to install. The dialog box also asks for a drive location where you want to install the JDK. The default location displayed is C:Program FilesJavajdk1.7.0_04, but you can use the Change button to select another location. Keep the default settings and click the Next button to continue. The selected program features are installed, followed by a dialog box that prompts for the destination folder to install the Java runtime environment (JRE), as shown in Figure 1.3.

Image

Figure 1.3. Dialog box prompting for the JRE installation location

The dialog box displays the default location for installing the JRE (C:Program FilesJavajre7). Use the Change button to place the program elsewhere. Keep the default location and select the Next button to continue. The Java files are copied and installed on your machine. If the installation is successful, a confirming dialog box is displayed. Select Finish to exit the wizard. After Java installation, the Android SDK Tools Setup Wizard automatically resumes.

If Java is already installed on your computer before beginning with Android SDK installation, the wizard detects its presence and displays the version number of the JDK found on the machine, as shown in Figure 1.4.

Image

Figure 1.4. Dialog box informing you that the JDK is already installed on the computer

Select the Next button. You get a dialog box asking you to choose the users for which Android SDK is being installed. The following two options are displayed in the dialog box:

Install for anyone using this computer

Install just for me

Select the Install for anyone using this computer option and click Next. The next dialog prompts you for the location to install the Android SDK Tools, as shown in Figure 1.5. The dialog also displays the default directory location for installing Android SDK Tools as C:Program Files (x86)Androidandroid-sdk, which you can change by selecting the Browse button. Keep the default directory for installing Android SDK Tools unchanged; then select the Next button to continue.

Image

Figure 1.5. Dialog box to specify the Android SDK Tools installation location

The next dialog box asks you to specify the Start Menu folder where you want the program’s shortcuts to appear, as shown in Figure 1.6.

Image

Figure 1.6. Dialog box to select the Start menu shortcut folder

A default folder name appears called Android SDK Tools. If you do not want to make a Start Menu folder, select the Do not create shortcuts check box. Let’s create the Start Menu folder by keeping the default folder name and selecting the Install button to begin the installation of the Android SDK Tools. After all the files have been downloaded and installed on the computer, select the Next button. The next dialog box tells you that the Android SDK Tools Setup Wizard is complete and the Android SDK Tools have successfully installed on the computer. Select Finish to exit the wizard, as shown in Figure 1.7.

Image

Figure 1.7. Successful installation of the Android SDK Tools dialog box

Note that the check box Start SDK Manager (to download system images) is checked by default. It means that after the Finish button is clicked, the Android SDK Manager, one of the tools in the Android SDK Tools package, will be launched. Android SDK is installed in two phases. The first phase is the installation of the SDK, which installs the Android SDK Tools, and the second phase is installation of the Android platforms and other components.

Adding Platforms and Other Components

In this step you see how to use the Android SDK Manager to download and install the important SDK packages required for the development environment. The Android SDK Manager (see Figure 1.8) that opens up shows the list of all the packages and their installation status. The dialog box shows that the Android SDK Tools package is already installed on the machine. To install any other package, you just need to check its check box. The Android SDK Manager recommends a platform by checking the Android 4.1 (API 16) and Google USB Driver package by default, which means the six components beneath the node will also be checked.

Image

Figure 1.8. Android SDK Manager showing the list of packages and their current status

You can check more packages and uncheck existing packages to determine which API you want to install. Because you want to work with the latest Android API, leave the default selected. Select all the packages listed under the Extras node as well, and choose the Install 7 packages button at the bottom to initiate installation. The next dialog box you see shows the list of the packages that you have selected to install, the package description, and license terms. You need to select the Accept All option, followed by the Install button to begin installation, as shown in Figure 1.9.

Image

Figure 1.9. Dialog box to accept the license terms for the selected packages and to begin installation

An Android SDK Manager Log window appears showing the downloading and installation progress. It also shows the list of packages that have been loaded, Android SDK Platform tools that have been downloaded and installed on the machine, and the ones that are still being downloaded (see Figure 1.10—left). After you select the Close button, the next dialog window is the ADB Restart window that provides information about updates and asks whether you want to restart ADB, as shown in Figure 1.10 (right). Select the Yes button in the dialog to restart ADB.

Image

Figure 1.10. Android SDK Manager Log showing the status of different packages (left), and the ADB Restart dialog box, prompting you to restart ADB (right)

You learn about ADB in detail later in this chapter. For now, it’s enough to know that ADB (Android Debug Bridge) is a command-line tool popularly used to communicate with emulator and Android devices.

The next dialog box is the Android SDK Manager, as shown in Figure 1.11. The dialog box confirms that the Android SDK Platform tools, Android 4.1 (API16), and its components have been successfully installed on your machine.

Image

Figure 1.11. Android SDK Manager showing that all the desired packages have been successfully installed on the machine

You don’t need the Android SDK Manager window for now, so you can go ahead and close it.

An Android application is a combination of several small components that include Java files, XML resource and layout files, manifest files, and much more. It would be very time-consuming to create all these components manually. So, you can use the following applications to help you:

Eclipse IDE—An IDE that makes the task of creating Java applications easy. It provides a complete platform for developing Java applications with compiling, debugging, and testing support.

Android Development Tools (ADT) plug-in—A plug-in that’s added to the Eclipse IDE and automatically creates the necessary Android files so you can concentrate on the process of application development.

Before you begin the installation of Eclipse IDE, first set the path of the JDK that you installed, as it will be required for compiling the applications. To set the JDK path on Windows, right-click on My Computer and select the Properties option. From the System Properties dialog box that appears, select the Advanced tab, followed by the Environment Variables button. A dialog box, Environment Variables, pops up. In the System variables section, double-click on the Path variable. Add the full path of the JDK (C:Program FilesJavajdk1.7.0_04injava.exe) to the path variable and select OK to close the windows.

Installing Eclipse

Eclipse IDE is a multilanguage software development platform commonly used for developing Java applications. You can add plug-ins to extend its features for developing applications in other languages. Eclipse can be downloaded from the following URL: http://www.eclipse.org/downloads/. The Eclipse Classic and the Eclipse IDE for Java Developers are recommended. Just remember that both the JDK and Eclipse must be for the same version, either 32 bit or 64 bit. The latest version, Eclipse Classic 3.7, is available at the time of this writing.


Note

To develop Android applications with Eclipse IDE, you need to extend its features by adding the Android Development Tools (ADT) plug-in to it.


Eclipse is a self-contained executable file—that is, all you need to do to install Eclipse is to unzip the downloaded file to any desired folder. To launch Eclipse, run the Eclipse.exe file. Eclipse IDE starts by displaying its logo, followed by a Workspace Launcher dialog box, as shown in Figure 1.12. The Workspace Launcher dialog prompts for the location of the workspace folder where the Eclipse project files will be stored. A default location is displayed that you can change by selecting the Browse button.

Image

Figure 1.12. The first screen you see after launching Eclipse IDE, asking for the Workspace location to save applications

The Use this as the default and do not ask again box can be checked if you don’t want Eclipse to prompt for the workspace every time it is launched. I recommend not checking this box, as it is better to have a separate workspace for each project to keep them organized. Select the OK button to continue. When Eclipse finishes loading, an Eclipse Welcome screen is displayed, as shown in Figure 1.13.

Image

Figure 1.13. Eclipse Welcome screen

Select the curved-arrow icon at the top right of the screen to go to the Workbench, as shown in Figure 1.14.

Image

Figure 1.14. The Eclipse Workbench, showing windows and panels

You can see that all the windows in the Workbench (Package Explorer, Editor window, Debug window, and Task List), are blank at the moment. These windows update their content as you develop Android applications. One more step is needed before you begin Android application development: installing the Android Development Tools (ADT) plug-in.

Installing the Android Development Tools (ADT) Plug-in

Android Development Tools (ADT) is a plug-in for the Eclipse IDE that provides a powerful, integrated environment to build Android applications. It makes the task of developing Android applications easy. It integrates with Eclipse to add functionality for creating, testing, debugging, and deploying Android applications.


Note

The ADT plug-in creates all the necessary base files required by the application.


To install the ADT plug-in, select the Help, Install New Software... option from the Eclipse IDE. You see a dialog box asking for the location of the website from which you want to install new software, as shown in Figure 1.15 (left). Select the Add button to add a website or repository location. An Add Repository dialog box appears, as shown in Figure 1.15 (right). Enter the name of the repository in the Name text box. Specify the name of the repository as ADT Plug-in, although it can be any other address. In the Location box, specify the location of the repository as https://dl-ssl.google.com/android/eclipse/ and click OK.

Image

Figure 1.15. The dialog box prompting for the location of the software installation website (left), and the dialog box to add the new repository information (right)

Eclipse accesses the list of developer tools available at the specified site and displays it, as shown in Figure 1.16. In the figure, you can see that an entry named Developer Tools is displayed, along with four child nodes: Android DDMS, Android Development Tools, Android Hierarchy Viewer, and Android Traceview. You need to install all four tools, so select the parent node, Developer Tools (its child nodes will be auto-selected), and select the Next button.

Image

Figure 1.16. Dialog box displaying the list of developer tools available in the added repository

You see a dialog box to Review Licenses for the ADT. Read the License Agreement, select the I accept the terms of the license agreements radio button if you agree with the terms and conditions, and select the Finish button, as shown in Figure 1.17.

Image

Figure 1.17. Dialog box to review and accept/reject the license agreement

The ADT plug-in is then downloaded and installed in Eclipse. After installation of the ADT plug-in, you get a Software Updates dialog box asking to restart Eclipse. To make the ADT plug-in show up in the IDE, you need to restart Eclipse. Select the Restart Now button from the Software Updates dialog box to make the installation changes take effect.


Note

If an older version of ADT is already installed in Eclipse, then instead of reinstalling, you just need to update it. Select Help, Check for Updates option. A new version of ADT is displayed, and you can update the ADT plug-in by copying and installing the new version.


Making the ADT Plug-in Functional

To make the ADT plug-in functional inside Eclipse, the plug-in needs to point to the Android SDK. Launch the Eclipse IDE and select the Window, Preferences option. In the Preferences dialog box, select the Android node (see Figure 1.18—left) and set the SDK Location field to specify the path where the Android SDK is installed on your disk (see Figure 1.18—right).

Image

Figure 1.18. (left) The Preferences window to specify the location of Android SDK installation, and (right) the list of supportable platforms displayed after specifying the location of the Android SDK installation

On specifying the path of the Android SDK, a list of SDK Targets is displayed. You can now develop and test Android applications against any of the displayed targets. You need to select the Apply button and click OK to reload the SDK Targets and close the Preferences window. Eclipse now has the ADT plug-ins attached.

The Android applications that you develop need to be tested and debugged before they are loaded on the actual Android device. The Android SDK provides several virtual devices that you can use to test and debug your applications.

Creating Android Virtual Devices

An Android Virtual Device (AVD) represents a device configuration. There are many Android devices, each with different configuration. To test whether the Android application is compatible with a set of Android devices, you can create AVDs that represent their configuration. For example, you can create an AVD that represents an Android device running version 4.1 of the SDK with a 64MB SD card. After creating AVDs, you point the emulator to each one when developing and testing the application. AVDs are the easiest way of testing the application with various configurations.

To create AVDs in Eclipse, select the Window, AVD Manager option. An Android Virtual Device Manager dialog opens, as shown in Figure 1.19. The dialog box displays a list of existing AVDs, letting you create new AVDs and manage existing AVDs. Because you haven’t yet defined an AVD, an empty list is displayed.

Image

Figure 1.19. The AVD Manager dialog

Select the New button to define a new AVD. A Create new Android Virtual Device (AVD) dialog box, appears (see Figure 1.20—left). The fields are as follows:

Name—Used to specify the name of the AVD.

Target—Used to specify the target API level. Our application will be tested against the specified API level.

CPU/ABI—Determines the processor that we want to emulate on our device.

SD Card—Used for extending the storage capacity of the device. Large data files such as audio and video for which the built-in flash memory is insufficient are stored on the SD card.

Snapshot—Enable this option to avoid booting of the emulator and start it from the last saved snapshot. Hence, this option is used to start the Android emulator quickly.

Skin—Used for setting the screen size. Each built-in skin represents a specific screen size. You can try multiple skins to see if your application works across different devices.

Hardware—Used to set properties representing various optional hardware that may be present in the target device.

Image

Figure 1.20. (left) Dialog to create new AVD, and (right) specifications of new AVD, demoAVD

In the AVD, set the Name of the AVD to demoAVD, choose Android 4.1—API Level 16 for the Target, set SD Card to 64 MiB, and leave the Default (WVGA800) for Skin. In the Hardware section, three properties are already set for you depending on the selected target. The Abstracted LCD density is set to 240; the Max VM application heap size is set to 48, and the Device RAM size is set to 512. You can select these properties and edit their values, delete them, and add new properties by selecting the New button. New properties can include Abstracted LCD density, DPad support, Accelerometer, Maximum horizontal camera pixels, Cache partition size, Audio playback support, and Track-ball support, among others. Finally, select the Create AVD button (see Figure 1.20—right) to see how to create the virtual device called demoAVD.


Note

You learn about the API and its different levels in Chapter 2, “Basic Widgets.”


The new AVD, demoAVD, is created and displayed in the list of existing AVDs, as shown in Figure 1.21.

Image

Figure 1.21. The newly created AVD listed in the AVD Manager


Note

The larger the allocated SD Card space, the longer it takes to create the AVD. Unless it is really required, keep the SD Card space as low as possible. I would recommend keeping this small, like 64MiB.


You now have everything ready for developing Android applications—the Android SDK, the Android platform, the Eclipse IDE, the ADT plug-in, and an AVD for testing Android applications. You can now create your first Android application.

Creating the First Android Project

To create an application, open Eclipse and choose File, New, Android Application Project or click the Android Project Creator icon on the Eclipse toolbar, or select the File, New, Other option. A dialog box appears asking you to select the wizard you want to use for the new application. Select Android Application Project and click Next. You see a dialog box asking for information about the new Android application, as shown in Figure 1.22 (left). In the Application Name box, enter the name of the application. Let’s name the application HelloWorldApp. The Project Name box shows the name of the project automatically by default. The project name assigned is the same as the application name, that is, HelloWorldApp. You can change the project name if desired. The Package Name box shows the default package name, com.example.helloworldapp. Let us enter the package name as com.androidunleashed.helloworldapp. The package name serves as a unique identifier for the application. A package name may contain uppercase or lowercase letters, numbers, and underscores. The parts of the package name may only begin with letters. The package name must be unique across all packages installed on the Android system. We use the syntax com.androidunleashed.project_name for the package names assigned to all the applications in this book. Remember, once an application is published, you cannot change the package name. If you change the application name, then it is considered to be a different application.

Image

Figure 1.22. Dialog box to specify the new project information (left), and configuring the launcher icon (right)

From the Build SDK drop-down, select the version of Android that represents the device most commonly used by your target audience. Let’s select the Android 4.1 (API 16) as the target platform. From the Minimum Required SDK select the minimum version of the Android platform that is required by the application to run. That is, the application will not run if the device’s API level is lower than the API level specified through this drop-down list. Select API 8: Android 2.2 (Froyo) from the Minimum Required SDK drop-down. It also means the application requires at least API 8 to run. Because this is a new project, select the Create Project in Workspace check box. By default, the Location where the application is stored on our disk drive is set to the workspace specified when opening Eclipse for the first time. Click Next to move further.

The next dialog, Configure Launcher Icon (see Figure 1.22—right), is used for configuring the icon for the application. The dialog shows three options—Image, Clipart, and Text—to define the icon for our application. The Clipart option is selected by default showing one of the built-in clipart. Select the Choose button to open the list of available clipart and then select one of them as our application’s icon. We can also select the Image option to specify the custom image to be used as our application’s icon. The Text option, when selected, displays a text box where we can enter text to represent our application. Select the Font button to change the font of the text and also to specify the font size and style. The dialog box also shows a Trim Surrounding Blank Space check box that we can select to remove the extra blank space around the chosen image, clipart, or text. A scrollbar is also provided to specify the padding around the icon. The icon can be set to appear at the center of the assigned space or can be cropped to accommodate the assigned space. The dialog also shows buttons to make the icon appear in a square or circle shape. Also, two buttons, Background Color and Foreground Color, are provided that display different colors that can be used as the foreground and background color of the icon. After defining the icon, click Next to move further.


Note

The Android Project Wizard automatically creates all the required files for the Android application.


The next dialog prompts us to select whether we want to create an activity. If we want to create an activity, the dialog box asks whether we want to create a BlankActivity or MasterDetailFlow activity (see Figure 1.23—left). The BlankActivity option creates a new blank activity, whereas the MasterDetailFlow option creates two master and detail fragments and two activities. We discuss activities and fragments later. To keep things simple, we go for blank activity for this application. Because, we want to create a blank activity, select the Create Activity check box and the BlankActivity option from the list and then click Next. The next dialog confirms the creation of the activity. The Android SDK assigns the default name MainActivity to the newly created activity. Also, the layout file is assigned the default name as activity_main. The Title assigned to the activity by default is MainActivity (see Figure 1.23—right). Let’s name the activity HelloWorldAppActivity. The layout filename and title name automatically change to reflect the newly assigned activity name. The layout name becomes activity_hello_world_app, and the Title of the application also changes to HelloWorldAppActivity. We can always change the auto-assigned layout filename and title of the application. Keeping the auto-assigned layout filename and the title unchanged, create the application by clicking Finish.

Image

Figure 1.23. Dialog box to select the type of activity to create (left), and specifying information of the newly created activity (right)


Note

The AVDs with newer SDKs can run applications that require older SDKs. The opposite is not true; that is, an application that requires a newer SDK will not run on an AVD with an older SDK.


The application is created, and the Package Explorer shows the files automatically created by the ADT plug-in, as shown in Figure 1.24.

Image

Figure 1.24. The Package Explorer displaying all the directories, subdirectories, and files automatically created for the application HelloWorldApp by ADT

You learn about the role of the different folders and their respective content in the next chapter. For now, we concentrate on the two files that play important roles in almost all Android applications:

The XML file, activity_hello_world_app.xml, found in the res/layout folder—The file that defines the user interface of the application. It contains controls such as TextView, Button, EditText, and CheckBox that are arranged on the display. The definitions in this file control how the user interacts with the application.

The Java file, HelloWorldAppActivity.java, found in the src folder—The file where action code of the controls defined in the layout file activity_hello_world_app.xml is written. Different events that occur via the controls in the layout file are handled with Java code. The data entered by the user is fetched and processed with this Java file.

The idea of separating the user interface from the action code is to isolate the presentation layer from the business logic, allowing developers to change the user interface without rewriting the code itself. As I talk about the XML and Java files, I will frequently use several terms described in Table 1.1.

Table 1.1. Common Terms

Image

Laying Out the Application

The screen of the application is defined by an XML file. The controls through which the desired information is displayed to the user and through which the user interacts with the application are defined in XML code. To define a screen of an application, you open the activity_hello_world_app.xml file, which is automatically created by the ADT plug-in in the res/layout folder. You can create more layout files to represent different screens of an application. All layout files are stored in the res/layout directory of the Android project. When you double-click on the activity_hello_world_app.xml file, you see the graphical layout of the application in the center window, as shown in Figure 1.25. The layout that you see is the default created by the ADT plug-in. There are two tabs at the bottom of the panel: Graphical Layout and activity_hello_world_app.xml. The Graphical Layout tab shows the layout in the Eclipse's Visual Designer, and the activity_hello_world_app.xml tab shows the XML code of the layout file.

Image

Figure 1.25. The layout file activity_hello_world_app.xml in the Visual Designer

Using the Visual Designer

The Visual Designer provided by Eclipse displays the layout file graphically. On the left side of the display, the designer shows a list of controls categorized in different categories. Through these controls, you can quickly design a screen. All you need to do is drag the desired control from the left side and drop it on the layout file. You can also configure the controls by settings their properties. The Properties panel is hidden by default. To make the Properties panel visible, select the Window, Show View, Other, General, Properties option. After you select a control, all its properties are displayed in the Properties panel.

Understanding the XML Version of the Layout File

The XML code of the layout file activity_hello_world_app.xml can be seen by selecting the activity_hello_world_app.xml tab at the bottom of the panel. The default code is shown in Listing 1.1.

Listing 1.1. Default Code in the Layout File activity_hello_world_app.xml


<RelativeLayout                                     #1
    xmlns:android="http://schemas.android.com/apk/res/android"       #2
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"                       #3
    android:layout_height="match_parent">
    <TextView                                              #4
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello"                       #5
        tools:context=".HelloWorldAppActivity" />
</RelativeLayout>


Statement #1 declares that all the controls are laid out in RelativeLayout. The RelativeLayout is the default layout and arranges the controls in relation to the existing controls. Layouts are also known as containers, as they hold and arrange the controls within them. You learn about the layouts in detail in Chapter 3, “Laying Out Controls in Containers.” Statement #2 defines the Android namespace. This attribute should always be set to http://schemas.android.com/apk/res/android. Namespaces are for assigning unique identifications to application elements, thus avoiding any collisions between element names. Even if you define another element in an XML schema with a name already in use in the Android API (to define its elements), collision will not occur, as they are defined in their respective namespaces.

Statement #4 defines the most basic UI control, TextView, which is commonly used for displaying information. In Android, the control that shows up on the screen and is used for displaying information and handling events is known as a View. The TextView that you see in the layout file (see Listing 1.1) is one of the most common views. You learn about more Views later in this book. All the Views are placed inside a container. The most common attributes required for laying out a screen view are layout_width and layout_height. These attributes are also known as LayoutParams in the Android SDK. The layout_width and layout_height attributes specify the width and height that a View can have. The two most common values for layout_width and layout_height are match_parent and wrap_content constants. The match_parent value in statement #3 tells the Android system to fill as much space as possible on the screen based on the available space of the parent layout. The wrap_content value tells the Android system to take up only as much space as needed to show the View. As the view’s content grows, the View’s viewable space also grows. Remember, the layout_width and layout_height attributes are essential attributes, and if you don’t provide values for these attributes, the Android application will crash when rendering the view. The value of the attributes android:layout_centerHorizontal and android:layout_centerVertical are set to "true" to make the TextView control’s text appear at the horizontal and vertical center of the view.

Statement #5 requires that the text to be displayed via the TextView control must be fetched from the strings resource file, strings.xml, defined in res/values folder. The text defined in the hello resource in the strings.xml file is assigned to the TextView for display. For now, let’s leave the resource files alone and talk about action code.


Note

For Android 2.2 and lower versions, match_parent was used as fill_parent. The option fill_parent is deprecated but is still supported for backward compatibility.


Defining Action Code Through Java

Recall that the Android application Java file is the Activity automatically created in the src folder by the ADT plug-in. An Activity represents a screen of the application and enables user interaction. While creating the application, you defined the Activity name as HelloWorldAppActivity; hence the Java file is named HelloWorldAppActivity.java. The default code in the Java activity file HelloWorldAppActivity.java is shown in Listing 1.2.

Listing 1.2. Default Code in the Java Activity File HelloWorldAppActivity.java


package com.androidunleashed.helloworldapp;

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

public class HelloWorldAppActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {        #1
        super.onCreate(savedInstanceState);                   #2
        setContentView(R.layout.activity_hello_world_app);    #3
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {           #4
        getMenuInflater().inflate(R.menu.activity_hello_world_app, menu);
        return true;
    }
}


The Java file is created and maintained in the package com.androidunleashed.helloworldapp that you defined at the time of application creation. The first statement of the code in Listing 1.2 confirms it. The file imports the desired class files and also inherits the Activity class. The onCreate() method is invoked when the Activity is started. It calls the onCreate() method of the super class (the Activity class) for initializing an activity.

In statement #1, the parameter Bundle savedInstanceState refers to a bundle used to pass information between different activities. Statement #2 is essential for activity initialization. If you don’t write this statement into the Java file, you get a runtime exception.

Statement #3 defines the screen (user interface) of the activity HelloWorldAppActivity. Basically, the user interface defined in the layout file activity_hello_world_app.xml is set as the content of an activity file. The parameter R.layout.activity_hello_world_app in the setContent() method refers to the activity_hello_world_app.xml file of the project’s res/layout folder. The character R in the parameter refers to the auto-generated R.java class file, which we discuss in the next chapter.

Statement #4 defines the onCreateOptionsMenu() method that is meant for dealing with menus. We learn about the menus in detail in Chapter 7, “Creating Interactive Menus and ActionBars.”

Let’s keep the existing default code of activity_hello_world_app.xml and HelloWordlAppActivity.java and run the application to see the output.

To run the application, you need to create an Eclipse launch configuration and choose a virtual device on which to run the application. The Android ADT provides two options for creating launch configurations:

Run configuration—Used to run an application on a given device

Debug configuration—Used to debug an application while it’s running on a given device

To create an Eclipse launch configuration, select the Run, Debug Configurations option. A Debug Configurations dialog box opens. Double-click the Android Application in the left pane (see Figure 1.26—left). The wizard inserts a new configuration named New_configuration, as shown in Figure 1.26 (right).

Image

Figure 1.26. (left) The Debug Configurations window, and (right) defining a new configuration through the Debug Configurations window

Let’s rename the configuration to HelloWorldApp_configuration. You need to specify the Android project name that you want to launch in the Project box. So, click the Browse button and choose the Android project HelloWorldApp. From the Launch drop-down list in the Launch Action section, select the Activity file com.androidunleashed.helloworldapp.HelloWorldAppActivity option, followed by the Apply button (see Figure 1.27—left). Next, you need to define a device on which to run the application. Select the Target tab in the same dialog box. You get the screen shown in Figure 1.27 (right).

Image

Figure 1.27. (left) Creating a new configuration called HelloWorldApp_configuration, and (right) defining the target AVD for the new configuration

The Deployment Target Selection Mode displays the following three options:

Always prompt to pick device—Allows you to choose the device or AVD to connect to when using this launch configuration.

Launch on all compatible devices/AVDs—Deploys the application automatically on all the compatible AVDs or devices available.

Automatically pick compatible device—Deploys the application on the AVDs that are selected. If none of the AVDs are selected, the application is launched on the compatible AVDs or devices available.

Select the third option, Automatically pick compatible device, followed by selecting the demoAVD that we created earlier to deploy the application automatically on this virtual device (see Figure 1.27—right). We select the demoAVD check box because we want to test the application against the Android 4.1 target. You can create more AVDs targeting other platforms from the AVD Manager window, and all the defined AVDs automatically appear in this dialog box, allowing you to select the desired target to test the application. After selecting the AVD, select the Apply button, followed by Close button, to save the launch configuration file.

Running the Application

Once the launch configuration file has been made, you can run the Android application by either selecting the Run icon from the Eclipse IDE toolbar, selecting the Run option from the Run menu, or pressing the Ctrl+F11 keys. Before displaying the application output, the emulator displays several boot screens. The first is shown in Figure 1.28 (left). The window’s title bar contains the port number of your computer on which the emulator is running (5554) and the AVD name (demoAVD). The second screen shows the Android logo, which is the same logo Android OS users see when they boot their phones. The second screen shows that the loading phase is complete and then displays the default locked Home screen, as shown in Figure 1.28 (right).

Image

Figure 1.28. (left) The first boot screen after running an application showing the Android logo, and (right) the second boot screen showing the default locked Home screen

To unlock the Home screen, either select the Menu button on the emulator, press the F2 key on your computer, or drag the lock to the right side and drop it over the other lock that appears there, as shown in Figure 1.29 (left). After the emulator is unlocked, the Home screen appears (see Figure 1.29—middle), followed by the output of the application, as shown in Figure 1.29 (right).

Image

Figure 1.29. (left) Dragging the lock to the right to unlock the Home screen, (middle) the emulator showing the Home screen, and (right) the output of the HelloWorldApp application

You can see that the application’s title, HelloWorldAppActivity, appears in the title bar of the emulator, and a text message, Hello world!, is displayed via the TextView control. The text to the TextView is assigned via the strings resource file, strings.xml. The output of the application confirms that the Activity is running correctly in the emulator.

If you feel that the screen shown by the emulator is too big, you can reduce it to the actual device size by selecting the Window, AVD Manager option. From the Android Virtual Device Manager dialog box that opens up (see Figure 1.30—left), select demoAVD and click the Start button. Select the Scale display to real size check box (see Figure 1.30—right) and then click the Launch button to start the emulator.

Image

Figure 1.30. (left) Select the AVD to scale to the real device size, and (right) setting options in the Launch Options dialog.

Don’t close the emulator screen; let it stay active to save the emulator’s loading time for running other applications. Whenever you run an application, the ADT checks for a running emulator and deploys it if found.

The Dalvik Virtual Machine (Dalvik VM)

While running Android applications, the Android runtime provides the Dalvik virtual machine that provides an environment to deploy and run Android applications. Dalvik VM is the Android platform’s virtual machine written by Dan Bornstein, who named it after a town in Iceland. Android applications run under this virtual machine. It is a specialized virtual machine designed specifically for Android and optimized for mobile devices with limited battery, memory, and computation capability. When you run an application, the Android SDK accesses all the layout and variable information in the XML files, converts it into Java source code, and places it in the R.java file. The Java code in the R.java class file is compiled into the Java byte code files (.class files), which, with the help of a tool named dx (included in the Android SDK), is converted into Dalvik byte code and stored in .dex format. The Dalvik Executable (.dex) format is optimized for efficient storage and low memory consumption.

Android applications are not deployed in dex format. Instead, the dex code is bundled into an APK file.

The Application Package (APK) File

The dex code that you get after converting the Java files is bundled with other required data and resources, including the manifest file AndroidManifest.xml into an Application Package (APK) file, which has an .apk extension. An APK file usually represents a single application and is used to distribute an Android application and install it on a mobile device or emulator. Each APK installed on an Android device is given its own unique ID that remains unchanged for as long as the APK resides on that device. An APK must be signed with a certificate whose private key is held by its developer.


Note

The Android Manifest file is an essential Android application configuration file. It contains the application startup information and its different components. You learn about the Android Manifest file and its content in detail in Chapter 2.


Using the TextView Control

So far, our HelloWorldApp contains default code. We simply ran the application whose default structure and code was created for us by the ADT plug-in. Now we learn to use the TextView control, removing the default text and entering our own. You can assign text to the TextView in two ways:

• Direct assignment to the TextView control as defined in the layout file activity_hello_world_app.xml

• Indirectly through the Java Activity file HelloWorldAppActivity.java

Assigning the Text Directly in the Layout File

The text that you want to be displayed through the TextView control can be assigned to it in its XML definition in the layout file activity_hello_world_app.xml. From the Package Explorer window, open activity_hello_world_app.xml by double-clicking it in the res/layout folder. Modify activity_hello_world_app.xml to appear as shown in Listing 1.3.

Listing 1.3. Code Written in the Layout File activity_hello_world_app.xml


<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">
     <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_centerHorizontal="true"
          android:layout_centerVertical="true"
          android:text="Hello World!"
           tools:context=".HelloWorldAppActivity" />
</RelativeLayout>


Notice that only the statement in bold has been modified. In the statement, android:text="Hello World!", the android:text is an attribute that is used for assigning a text to the given control. The text Hello World! is assigned to the TextView control through the android:text attribute. You learn about more attributes later in this chapter. Let’s run the application to see the impact of changing the TextView control’s text. You get the output shown in Figure 1.31 (left). The output displays the text, Hello World!, that you assigned to the TextView control. To make the message “Hello World!” appear at the top-left corner of the screen (see Figure 1.31—right), remove the two attributes android:layout_centerHorizontal and android:layout_centerVertical from the <TextView> tag in the preceding layout file followed by running the application.

Image

Figure 1.31. (left) Text message Hello World! displayed at the center of the screen by setting an attribute in the XML definition, and (right) text message Hello World! appears at the top-left corner of the screen.

Let’s now try out the alternate method of assigning text to the TextView control by using the Java Activity file.

Assigning Text Through the Activity File

To assign text to the TextView control through the Java Activity file HelloWorldAppActivity.java you need to do the following two things:

Remove the text from XML definition—The first thing that you need to do is to remove the text that was assigned to the TextView control in the layout file activity_hello_world_app.xml. Open the activity_hello_world_app.xml file and remove the statement android:text="Hello World!". The TextView control will appear blank and will not display anything on execution.

Assign an ID to the TextView control—To access the TextView control in the Activity file, you have to uniquely identify it by assigning it an ID. To assign an ID to a control, use the android:id attribute. Add the following statement to the TextView tag in the activity_hello_world_app.xml file:

android:id="@+id/message"

This statement declares that a constant called message is assigned as an ID to the TextView control and will be used to uniquely identify it from other Views. The plus sign (+) in @+id/message means that the ID, message, must be created if it doesn’t already exist.

After you remove the android:text and add the android:id attribute to the TextView tag, the layout file activity_hello_world_app.xml appears as shown in Listing 1.4.

Listing 1.4. Code Written in the Layout File activity_hello_world_app.xml


<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" >
     <TextView
          android:id="@+id/message"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          tools:context=".HelloWorldAppActivity" />
</RelativeLayout>


After you assign an ID to the TextView control, it will be accessible in the Activity file. To assign text to the TextView control through HelloWorldAppActivity.java, modify it to appear as shown in Listing 1.5.

Listing 1.5. Code Written in the Java Activity File HelloWorldAppActivity.java


package com.androidunleashed.helloworldapp;

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

public class HelloWorldAppActivity extends Activity {
@Override
     public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.main);
          TextView mesg = (TextView)findViewById(R.id.message);   #1
          mesg.setText("Hello World!");                           #2
    }
}


Statement #1 locates the control with the message ID in the layout file by using the findViewById method of the Activity class and maps it to the TextView object, mesg. It means the mesg object now represents the TextView control with the message ID in the layout file. Statement #2 assigns the text Hello World! to mesg object and hence to the TextView control. Because we are not dealing with any menu, we erased the onCreateOptionsMenu() method from the preceding activity file, which was provided by default.

On running the application, you see the same output shown in Figure 1.31 (right). Let’s assign a few more attributes to the TextView control and change its height, width, color, style, background, and alignment. Android provides several units of measurement for specifying the dimension when setting the size of controls. Before you begin applying different attributes to the TextView control, let’s have a brief look at the allowable units of measurements used in dimensioning controls.

Applying Dimensions to Controls

Dimensions are commonly used to specify the size and other properties for the controls and layouts. As you design the user interface, you often specify a dimension for a control or layout. The following units of measurements are used:

px (pixels)—Corresponds to the actual pixels on the screen.

in (inches)—Based on the actual size of the screen.

mm (millimeters)—Based on actual size of the screen.

pts (points)—Points are a fixed dimension—1/72 of an inch.

dip or dp (device-independent pixels)—Based on the physical density of the screen. This unit is relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp to pixel changes with the screen density. For example, on a 240 dpi screen, 1 dp is equal to 1.5 pixels.

sp (scale independent pixels)—Similar to the dp unit, but also depends on the user’s font size settings. Hence this unit is preferred while specifying font sizes.


Note

Using the px unit is not recommended, as the UI may not render correctly on a device with a different screen resolution.


To align the content within the control, the gravity attribute is used. Let’s go ahead and discuss it.

Aligning Content with the Gravity Attribute

The gravity attribute is used for aligning the content within a control or its container. For example, to align the text of the TextView control to the center, you set the value of its android:gravity attribute to center. Some of the valid values for the android:gravity attribute are shown in Table 1.2.

Table 1.2. Values Used in the Gravity Attribute

Image

You can combine two or more values of any attribute using the '|' (pipe character). For example, the following example centrally aligns the text horizontally as well as vertically within a control:

android:gravity="center_horizontal|center_vertical"

If you want to apply the gravity attribute to any control through the Java activity file, the Java method used for this purpose is setGravity().

Commonly Used Attributes

Table 1.3 lists the attributes commonly applied to configure the controls.

Table 1.3. List of Commonly Used Attributes

Image
Image
Image

Let’s apply some of the attributes shown in the Table 1.3 to the TextView control (in activity_hello_world_app.xml) of the HelloWorldApp application, as shown in the following example:

<TextView
    android:id="@+id/message"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".HelloWorldAppActivity"
    android:typeface="serif"
    android:textColor="#0F0"
    android:textSize="25dp"
    android:textStyle="italic"
    android:gravity="center_horizontal" />

This code makes the text of the TextView control appear in serif font, green color, 25dp size, italic, and at the horizontal center of the container, as shown in Figure 1.32 (left).

Image

Figure 1.32. (left) Text message formatted with different attributes and displayed via TextView control, and (right) the text of TextView wrapped to the next line


Note

The “dp” unit represents density-independent pixels based on a 160-dpi (pixel density per inch) screen. We learn more about units in Chapter 4.


Let’s apply a few more attributes to the TextView control here:

<TextView
    android:id="@+id/message"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context=".HelloWorldAppActivity"
    android:gravity="center"
    android:height="200dp"
    android:width="150dp"
    android:typeface="serif"
    android:textColor="#0F0"
    android:textSize="25dp"
    android:textStyle="bold"  />

This code makes the content of the TextView wrap move to the next line if the width assigned to it is insufficient. The TextView control is assigned the height and width of 200dp and 150dp, respectively, and its text is set to appear at the center of its assigned size. The text appears in serif font, green color, 25dp font size, and bold. The text in the TextView appears as shown in Figure 1.32 (right).

Using the Android Emulator

The Android emulator is used for testing and debugging applications before they are loaded onto a real handset. The Android emulator is integrated into Eclipse through the ADT plug-in.

Limitations of the Android Emulator

The Android emulator is useful to test Android applications for compatibility with devices of different configurations. But still, it is a piece of software and not an actual device and has several limitations:

• Emulators no doubt help in knowing how an application may operate within a given environment, but they still don’t provide the actual environment to an application. For example, an actual device has memory, CPU, or other physical limitations that an emulator doesn’t reveal.

• Emulators just simulate certain handset behavior. Features such as GPS, sensors, battery, power settings, and network connectivity can be easily simulated on a computer.

• SMS messages are also simulated and do not use a real network.

• Phone calls cannot be placed or received but are simulated.

• No support for device-attached headphones is available.

• Peripherals such as camera/video capture are not fully functional.

• No USB or Bluetooth support is available.

The emulator provides some facilities too. You can use the mouse and keyboard to interact with the emulator when it is running. For example, you can use your computer mouse to click, scroll, and drag items on the emulator. You can also use it to simulate finger touch on the soft keyboard or a physical emulator keyboard. You can use your computer keyboard to input text into UI controls and to execute specific emulator commands. Some of the most commonly used commands are

• Back [ESC button]

• Call [F3]

• End [F4]

• Volume Up [KEYPAD_PLUS, Ctrl-5]

• Volume down [KEYPAD_MINUS, Ctrl-F6]

• Switching orientations [KEYPAD_7, Ctrl-F11/KEYPAD_9, Ctrl-F12]

You can also interact with an emulator from within the DDMS tool. Eclipse IDE provides three perspectives to work with: Java perspective, Debug perspective, and DDMS perspective. The Java perspective is the default and the one with which you have been working up to now. You can switch between perspectives by choosing the appropriate icon in the top-right corner of the Eclipse environment. The three perspectives are as follows:

The Java perspective—It’s the default perspective in Eclipse where you spend most of the time. It shows the panes where you can write code and navigate around the project.

The Debug perspective—Enables application debugging. You can set breakpoints; step through the code; view LogCat logging information, threads, and so on.

The Dalvik Debug Monitor Service (DDMS) perspective—Enables you to monitor and manipulate emulator and device status. It also provides screen capture and simulates incoming phone calls, SMS sending, and GPS coordinates.

The Debug perspective and DDMS are discussed in detail in Chapter 5, “Using Selection Widgets and Debugging.” To manage content in the device or emulator, you can use the ADB (Android Debug Bridge).

The Android Debug Bridge (ADB)

The Android Debug Bridge (ADB) is a client-server program that is part of the Android SDK. It is used to communicate with, control, and manage the Android device and emulator.

It consists of three components:

Client—Runs on a computer machine. It can be invoked from the command prompt using the adb command.

Daemon—Runs as a background process in either an emulator instance or in the device itself.

Server—Runs in a computer machine in the background. It manages the communication between the client and the daemon.

When you install the Android SDK, the Android Debug Bridge is also automatically installed along with it. When the Android Debug Bridge is active, you can issue adb commands to interact with one or more emulator instances. You can install applications, push and pull files, and run shell commands on the target device. Using the shell commands, you can perform several tasks such as listing existing applications, deleting applications, and querying or modifying SQLite databases available on the device.

To access ADB through Windows, open the command prompt and navigate to the folder where adb.exe is located by using the cd command. By default, adb.exe is installed in C:Program Files (x86)Androidandroid-sdkplatform-tools. When you are in the folder where adb is found, you can issue the following commands to interact with the device or emulator:

adb devices—Displays the list of devices attached to the computer. Figure 1.33 shows the currently running emulator on your computer, emulator-5554.

Image

Figure 1.33. Output of different commands issued through ADB

adb push—Copies files from your computer to the device/emulator.

Syntax:

adb push source destination

where source refers to the file along with its path that you want to copy, and destination refers to the place in the device or emulator where you want to copy the file. Figure 1.33 copies the mp3 file, song1.mp3, from local disk drive D: to the sdcard folder of the running emulator.

adb pull—Copies files from the device/emulator to your computer.

Syntax:

adb pull source [destination]

Figure 1.33 shows how the song1.mp3 file can be copied from the sdcard of the emulator to the android folder on local disk drive E:.

adb shell—Displays the shell prompt where you can issue Unix commands. You can see the names of different files and folders of the emulator after issuing an ls command (see Figure 1.33).

You can issue the commands to list, rename, and delete applications from the emulator. For example, to delete the file song1.mp3 that you pushed into the emulator, you issue the rm command, as shown in Figure 1.33.

Leave the shell; press Ctrl+D.

adb install—Installs an application from your computer to the device/emulator.

Syntax:

adb install appname.apk

This code

C:Program Files (x86)Androidandroid-sdkplatform-tools>adb install D:
androidunleashedloginApp.apk

installs the application package file loginApp.apk into the emulator.

Let’s conclude the chapter by understanding how an Android application is launched on a physical device.

Launching Android Applications on a Handset

To load an application onto a real handset, you need to plug a handset into your computer, using the USB data cable. You first confirm whether the configurations for debugging your application are correct and then launch the application as described here:

1. In Eclipse, choose the Run, Debug Configurations option.

2. Select the configuration HelloWorldApp_configuration, which you created for the HelloWorldApp application.

3. Select the Target tab, set the Deployment Target Selection Mode to Manual. The Manual option allows us to choose the device or AVD to connect to when using this launch configuration.

4. Apply the changes to the configuration file by clicking the Apply button.

5. Plug an Android device into your computer, using a USB cable.

6. Select Run, Debug in Eclipse or press the F11 key. A dialog box appears, showing all available configurations for running and debugging your application. The physical device(s) connected to the computer are also listed. Double-click the running Android device. Eclipse now installs the Android application on the handset, attaches a debugger, and runs the application.

Summary

In this chapter, you saw how to install the Android SDK Starter Package, add platforms and other components, and install Eclipse and the Android Development Tools (ADT) plug-in. You made the ADT plug-in functional and created Android Virtual Devices to run and deploy Android applications. You learned how to create a First Android Project and set the layout of the application. The XML version of the layout file was described, and you learned how to define action code through Java. You were introduced to the concept and usage of different tools such as Dalvik VM, APK, ADB, and the Android Emulator. You learned to use the TextView control in the application and assign text to it via the layout and activity files. You also learned about the usage of commonly used attributes of controls, including the gravity attribute. Finally, you learned the steps to launch an application on a handset.

The next chapter focuses on the basic widgets used in an Android application. You learn about

• Folders and files that are automatically created by the ADT plug-in

Activities, the Android Activity life cycle, usage of Android Manifest file, commonly used layouts and controls, and how event handling is performed

• How to create an anonymous inner class, implement the OnClickListener interface, and declare the event handler in the XML definition of the control

• How to create and start your own Activity, Intent, create your own layout file, create a new Activity, register the new Activity, and start the Activity

• How to use three controls—EditText, CheckBox, and RadioButton—and develop Android applications using these controls

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.235.63