Chapter     4

Introducing the Android Software Development Platform

The Android platform is a collection of software that includes an operating system and a number of higher-level libraries that simplify the task of communicating with the operating system. It also includes several applications that smartphone, tablet, e-reader and iTV users have come to expect, such as a phone (obviously) dialer, e-mail client, social media client, contact manager, Google Maps, Google Search, a web browser, a calendar, basic games, and so on.

Everything in the Android development environment, as well as all of the included applications, can be programmed with a combination of Java and XML thanks to the so-called runtime that is included with the Android SDK. The runtime translates the Java and XML code that you write into a language that the operating system and the device understand.

The foundation on which Android is built is carefully coded and painstakingly tested Linux 2.6, an operating system that rarely crashes. Linux and its core services manage the physical phone, tablet, e-book e-reader, or iTV set and give Android applications complete access to the features of each consumer electronics device, including the touchscreen, memory, data, security, various network receivers and transmitters, camera, GPS, Bluetooth, Wi-Fi, and more.

Linux doesn’t do it all alone. Android has a large number of libraries that provide higher-level customized functions and services for 2D graphics, 3D graphics, and the audio and video file formats in widest use today. In other words, Android supports all of the rich media formats you could possibly want to use, including the powerful ON2 VP8 video codec, now in Android 4.x (for more information, visit: http://developer.android.com/guide/appendix/media-formats.html). ON2 was acquired by Google and rereleased as an open codec called WebM for HTML5 and Android. It’s quality to file size (and thereby performance) ratio is impressive to say the least.

This chapter introduces the Android 4 software development environment, and shows you how to write your first Android application.

Note  In this book, you’ll build apps using a combination of XML and Java, which sit in a layer on top of the operating system (with the runtime as the component that translates Java and XML into instructions for the operating system). However, you could, if you wished, access the operating system and its services directly, using lower-level languages such as C or C++ using the Android NDK, or native development kit, rather than the higher level software development kit, or SDK, that we are using for this book. You might consider this “under the hood” approach for an application that needs the utmost speed, such as a 3D game or a real-time heart-monitoring program, but the NDK is far beyond the scope of this introductory book.

Understanding Java SE and the Dalvik Virtual Machine

The Android runtime environment provides a core set of operating system libraries that can be accessed via Java and XML. These give you access to device features and lower-level Android operating system functions so that you don’t have to do any of that hard programming yourself. You simply include the appropriate components from the libraries you need in your program—something called importing—and then your application code can employ their built-in capabilities. You’ll learn how to put a significant number of these powerful code engines to work in later chapters.

To run Java SE code, Android uses a tool called the Dalvik Virtual Machine (DVM). The DVM is an optimization mechanism and technology that allows application code and resources to be highly optimized for use in mobile and embedded environments.

Embedded environments are ones in which a computer is actually embedded inside the consumer electronics product, and this is now commonplace in smartphones, tablets, e-book e-readers, iTV sets, and iDVD players, to name a few. I’ve also seen phone-watches and smart appliances (refrigerators); so it’s not limited to Internet 2.0 (portable or mobile) devices either!

The good news is that the DVM is not something that a developer needs to worry about. I describe it here only to give you a sense of what’s going on under the hood with Android.

When you launch an Android application, it creates a process that allocates memory and CPU processing resources (processor time slices) to the application, so that it has the resources needed to function. Each time an application is launched and a process is spawned, an instance or copy of the DVM is launched into your Android smartphone, iTV, or tablet’s memory. The DVM actually takes the Java language instructions along with the application’s design guidelines (in an XML format), and combines them with any external resources (images, audio or video files, 3D, and so on), and translates them all into optimized low-level binary code that goes into the Android device’s memory and eventually into the processor for processing.

So, what is the advantage of this DVM? Using DVM allows many more applications to run within the somewhat limited memory resources (1GB to 2GB) and processing power (1GHz to 2GHz) of consumer electronic devices, and it also protects all of the other spawned (active in memory) processes from interfering with each other. In this way, the crash of one application will not bring down the entire operating system (as happened in the olden days of DOS and Macintosh). That’s a huge advantage, because other apps cannot take down your app, or heaven forbid, vice-versa.

The Directory Structure of an Android Project

Android does its best to externalize all application assets that do not absolutely need to be in your Java code. It does this by using the simpler XML markup language to define UI (user interface) designs and data structures that would otherwise need to be explicitly declared and coded in Java. This modularization is aided and implemented by having a clearly defined project hierarchy folder structure, which holds logical types of application assets together in an orderly fashion.

Because Android is very particular about where the assets of your project are stored within the project directory, you need to learn where each belongs early in the game. When it comes time to generate your application—a process called compilation—Android looks into these standardized folders to locate each type of asset it needs, and expects to find, like assets logically grouped together.

The assets of a project include its Java code, XML layouts, XML animation definitions, and the rich media files that your Java code and XML markup reference. As shown in Figure 4-1, default folders are automatically created in an Android project to hold menus, images, layouts, colors, fixed data values, raw (uncompressed) media, XML constructs, and animation. These default folders will be created by the Android Developer Toolkit (ADT) New image Project image Android Application Project function that we installed and tested in Eclipse 4.2.1 at the end of Chapter 3.

9781430247883_Fig04-01.jpg

Figure 4-1 .  Android’s file structure, showing the res (resources) folder and its subfolders

The Java code that drives an application is located in the /src (source code) folder and in any subfolders that are defined by your Java code.

You’ll find other assets used by your application in logical subfolders of the /res (resources) folder as needed. It is very important that only folders go in the /res folder. If the Android compiler sees any files in this folder, it will generate a compiler error.

Note  The name of the game is to avoid compiler errors at all costs because if Eclipse sees compiler errors in your code, it does not even bother generating your application. And if your application is not generated, you certainly cannot test it to see how well it works.

If you don’t have any resources of a certain type (say animation), you do not need to have an empty folder for it. This means that you do not need to create folders that you will not use.

Common Default Resources Folders

The most common of the default resources (/res) subfolders are shown in the Figure 4-1. The following are the eight provided when you create a project in Eclipse:

  • layout: UI screen layouts go in the /res/layout folder, which holds XML files containing UI layout definitions written in XML.
  • drawable-hdpi : high-resolution images in PNG format (which Google prefers) or the JPEG format (acceptable but not favored by Google) go into the /res/drawable-hdpi (high resolution screen-drawable imagery, usually 800 by 480 pixels) folder.
  • drawable-ldpi : low-resolution images in PNG format (which Google prefers) or the JPEG format (acceptable but not favored by Google) go into the /res/drawable-ldpi (low resolution screen-drawable imagery, usually 320 by 240 pixels) folder.
  • drawable-mdpi: medium-resolution images in PNG format (which Google prefers) or the JPEG format (acceptable but not favored by Google) go into the /res/drawable-mdpi (medium resolution screen-drawable imagery, usually 480 by 320 pixels) folder.
  • drawable-xhdpi: extra-high-resolution images in PNG format (which Google prefers) or the JPEG format (acceptable but not favored by Google) go into the /res/drawable-xhdpi (high resolution screen-drawable imagery, usually 1,280 by 720 pixels or HD)  folder
  • values: XML files that define constant values are in the res/values folder.
  • values-v11 : honeycomb theme XML files that define new UI theme values are in the res/values-v11 (referencing API Level 11 through 13, also known as Android 3.x or 3.0, 3.1, and 3.2) folder.
  • values-v14: Ice Cream Sandwich theme XML files that define new UI theme values are in the res/values-v14 (referencing API Level 14 through 16, also known as Android 4.x or 4.0, 4.0.3, and 4.1) folder.
  • menu : XML files defining menu layouts are in the res/menu folder.

The Values Folder

Let’s examine the res/values folder from one of my current projects in more detail. This is where you place predefined application values in the form of XML files that define the variable names (x or y, for instance) and their values that are later referenced in your Java code. For example, these values might be strings (collections of text characters) or constants (hard-coded values that your Java code uses in its program logic and can’t change).

Think of the values folder as holding all of your constant values for your application in one place. This way, if you need to adjust them during application development and testing, you make the changes in a single location.

Figure 4-2 shows a few examples of files that can be placed in this folder as in the following:

9781430247883_Fig04-02.jpg

Figure 4-2 .  Files in the res/values folder. These files contain constants for an Android application

  • colors.xml: An XML file that will define the color values to be used in the app. These allow you to standardize the UI. For example, you would define your background color. Then, if you decide to tweak it later, you need to do the tweaking in only one place.
  • dimens.xml: An XML file that defines dimension values, such as standard heights and font sizes for your UI. You can then use these values across your app to ensure it is consistent.
  • arrays.xml: An XML file that defines a series of values to be used together (known as an array). For example, this could be a list of icon files or a list of options to display to the user.
  • strings.xml: An XML file that defines text strings to be used in the application. For example, you can place any screen titles or the app’s name here and reference them in your code. If you need to change these items, you simply do it here rather than in your code.
  • styles.xml: An XML file that defines styles to be used in the application. These styles are then applied to the UI elements that require them, so you separate the look of your app from the layout and functionality. This makes your app easier to maintain.

Notice the Android file name conventions for the different types of XML files in the values folder, adding another level of complexity.

Leveraging Android XML (Your Secret Weapon)

One of the most useful features of Android as a development environment is its use of XML to define a great number of attributes within your application’s infrastructure. Because you don’t need to work inside the Java programming language to handle these attributes, you save hundreds of lines of Java code. Everything within the application—from your UI layouts, to your text strings, animation, or inter-process communication with Android’s operating system services (like vibrating the phone or playing a ringtone)—can be defined via XML.

What makes XML ideal for Android development, and especially for beginners, is its ease of use. It is no more complicated than HTML markup. So, if you know how to use tags to boldface text or insert an image in your website, you already understand how to use XML.

You will be learning how this works in the next chapters of the book. Suffice it to say that you will become familiar with XML in your Android development. XML brings a lot of flexibility to Android development.

Android’s use of XML for application design is very similar to the way HTML, cascading style sheets (CSS), and JavaScript are used in today’s popular Internet browsers. CSS is used to separate the layout and look of a web page from its content and behavior, which are specified by HTML markup and JavaScript code, respectively. This approach leads to more modular and logically structured web pages. Designers can work on the look of a website using CSS, while search engine optimization (SEO) professionals optimize its findability with HTML, leaving user interaction to programmers who know how to use JavaScript. The same approach applies to Android. Designers can create the UI for an application with XML, while programmers can call and access its elements using Java without affecting screen formatting, animation, or graphics. Genius.

XML gives us amazing flexibility to accommodate variations within our apps, such as different screen sizes, languages, themes, and UI designs. Here, we’ll look at a couple of brief examples to give you an idea of XML’s power.

Screen Sizes

Because UI designs can be defined precisely by an XML file, it’s easy to deal with the variety of screen sizes available on Android devices today. Let’s say that you want to do a custom layout for each of the four primary screen sizes used in Android phones:

  • Quarter VGA (QVGA), 240 × 320 pixels also known as low DPI or LDPI
  • Half VGA (HVGA), 320 × 480 pixels (the “sweet spot” for low-cost  Android phones) also known as medium DPI or MDPI
  • Wide VGA (WVGA), 800 × 480 pixels (found on the newer phones and now a common tablet and e-reader resolution) also known as High DPI or HDPI
  • Wide SVGA (WSVGA), 1,024 × 600 pixels (found on the newest smartphones and tablets) also known as extra high DPI or XHDPI
  • HDTV 1280 x 720 and 1920 x 1080 (found on HD smartphones, tablets, e-readers and iTVs) also known as TVDPI

How does XML provide a solution? Simply create a UI design in XML for each size and use Java to determine the screen resolution of the phone. We also noted in the previous section that Android provides drawable folders for the graphics file assets for each of these standard screen resolutions, so be aware that you must develop graphics for at least four different screen size targets for your Android applications. No one said that Android applications development was going to be easy!

Desktop Clocks

As another example of how XML can be leveraged, let’s take a look at a few lines of code that define an important utility: Android’s popular desktop clock. (In Chapter 6, you’ll learn how to create your own custom desktop clocks.)

The XML tag for an Android program function usually has the same name as its Java counterpart, so you can access the power of the programming language from simple XML. For example, here is the XML tag that corresponds to Java’s AnalogClock:

<AnalogClock />

Android’s XML tags start with a left-angle bracket (<), followed immediately (no space) by a class name, a space, a slash mark, and a right-angle bracket (/>).

To customize an AnalogClock, you must add attributes to the AnalogClock tag, inserting them before the closing part of the tag (/>). Suppose you want to add an ID to reference the utility from other parts of the application. Here’s how:

<AnalogClock android:id="@+id/AnalogClock" />

This adds an ID to your AnalogClock with the name AnalogClock, which you can use to reference it elsewhere in your application.

For each XML tag in Android, there are dozens of parameters that allow you to control the tag’s appearance and implementation, including its positioning, naming (used in the Java code), and other options.

In real-life, for readability, programmers usually write this code with each configuration parameter indented on a separate line, like this:

<AnalogClock
        android:id="@+id/AnalogClock"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
/>
The Android compiler considers everything inside the AnalogClock tag to be a parameter, or a customization option, until it reaches a closing tag (/>). The fill_parent parameter stretches content to fill a container, and the wrap_content parameter shrink-wraps the content. We’ll cover these and other view and layout concepts later on in Chapters 6 and 7.

Using Your Android Application Resources

In addition to Java code and XML markup, the resources your application draws on consist primarily of new media elements and other file types that contribute to its functionality in one way or another. These may include XML files that contain animation parameters or text strings, bitmap image files, and even audio and video files (audio and video “streams” on the other hand are external to an app and come from a server, and thus are not a resource in this context).

One of the primary reasons for externalizing resources is that you can have sets of resources for variations, such as different screen sizes or language versions. Language localization localizes the application to any given country. These language localizations can be easily referenced in the Java code and switched when necessary by pointing to different external file names or folders.

Bitmap Images

Let’s look at an example of a common application resource: the bitmap image. Your PNG or JPEG bitmap image goes into its proper /res/drawable folder depending on its pixel dimensions. It can then be referenced by its file name only (excluding its extension) in the Java code, as well as in XML. For this important reason, be sure not to give a PNG file and a JPG file the same name, or you will have problems when it comes time to compile your code.

Also, contrary to normal file-naming conventions, image file names can contain only numbers, an underscore character, and lowercase letters, so make sure to remember this rule (one of the many anomalies of Android programming).

In summary, to set up bitmap images to be used in your application, do the following:

  • Name them correctly, using only numbers, underscores, and lowercase letters.
  • Use the PNG or JPG format, or WebP if you are creating apps for the Android 4 or later (4.0, 4.0.4, and 4.1) platforms only.
  • Make sure they are in the proper /res/drawable folder, based on their pixel dimensions, so that Android can find them.

Alternate Resource Folders

Another great example of resource usage is supplying different UI screen layouts for portrait and landscape orientations. Usually, we will set our default screen UI for phones to portrait mode, as most people use their phone in this way (turning it sideways only to view video).

Android provides support for alternate resources. If you set them up correctly, Android will determine the current settings and use the correct resource configurations automatically. In other words, you provide resources for each orientation, and Android uses the correct resources as the user changes from one orientation to another.

Each set of alternative resources is in its own folder, where it can be referenced and located later on in your Java code. We can provide resources for different screen orientations and resolutions in this fashion, and have Android decide which folders to look in for our application resources based on each user’s smartphone, tablet, or e-reader model.

Android currently offers four screen resolutions: low resolution (320 × 240), medium resolution (480 × 320), high resolution (800 × 480) and extra high resolution (1,024 × 600 or 1,280 × 720). Look for a fifth TVDPI resolution 1,920 × 1,080 classification to be added in Android 4.2 to accommodate Google TV and HD iTVs. Note that you can always add your own alternate resources folders now, Android just creates the /drawable-ldpi folders for you as a convenience and to remind you to provide graphics for all the common device screen sizes, but if you were doing an iTV app you could create a /drawable-tvdpi folder yourself and reference it from your app.

To add an alternate resource folder, create a directory under /res with the form <resource_name>−<config-qualifier>. For instance, android created /res/drawable-hdpi for you in its New Project Creation Process, to hold your high DPI resolution drawables or images.

This created an alternate resource folder for high-density dots per inch (hdpi) images. The alternate folder will be used automatically if the Android smartphone screen uses a WVGA (800 × 480) screen high-end model. Otherwise, it will use the normal HVGA (320 × 480) screen images, located in the default /res/drawable-mdpi folder, if the device screen resolution is not automatically detected.

If you want to also support low-end screens, you can use the low-density dots per inch qualifier, ldpi. There is a medium-density dots per inch qualifier, mdpi, as well as an extra high dots per inch qualifier called xhdpi.

So, to have images for QVGA, HVGA, WVGA, and WSVGA screens arranged into folders in a way that allows Android to automatically recognize the folder hierarchy, set up your folder structure as follows:

  • /res, with only subfolders, place NO individual files in this folder
  • /res/drawable-ldpi, with the following low-density DPI (120 DPI) screen images (QVGA):
  • ic_launcher.png (application icon file), 36 × 36 pixels
  • background.png (application background), 320 × 240 pixels
  • /res/drawable-mdpi, with the following medium-density DPI (160 DPI) screen images (HVGA):
  • ic_launcher.png, 48 × 48 pixels
  • background.png, 320 × 480 pixels
  • /res/drawable-hdpi, with the following high-density DPI (240 DPI) screen images (WVGA):
  • ic_launcher.png, 72 × 72 pixels
  • background.png, 800 × 480 pixels
  • /res/drawable-xhdpi, with the following extra-high-density DPI (320 DPI) screen images (WSVGA or HDTV):
  • ic_launcher.png, 96 × 96 pixels
  • background.png, 1,024 × 600 or 1,280 × 720 pixels

Note that there are two HDTV resolution graphics standards, HDTV 1,280 by 720 and True HD 1,920 by 1,080. You’re well on your way to correctly setting up your Android application’s resources. One more file we need to examine is AndroidManifest.xml.

Launching Your Application: The AndroidManifest.xml File

When Android launches your application, the first file it seeks out is the application manifest file. This file is always located in the root of your project folder and directory structure, and is always called AndroidManifest.xml so that it can be located easily on startup.

The Android manifest declares some very high-level definitions and settings for your application using (surprise!) the XML markup language. The following are some of the key items AndroidManifest.xml includes:

  • References to the Java code you will write for your application, so that your code can be found and run.
  • Definitions of the components of your Android application, including when they can be launched.
  • Definitions of permissions for application security and for talking with other Android applications.
  • Declaration of the a minimum level of Android operating system version support, which amounts to defining which version(s) of Android your application is going to support.

All of the apps to be written in this book will support Android versions 2.2, 2.3.7, 3.0, 3.1, 3.2, 4.0, 4.0.4, and 4.1.2. We call this “Android API Level 8 through 16 compatibility” because it supports every version of Android from Version 2.2 (Froyo) through the current Version 4.1.2 (Jelly Bean).

Tip  I try to develop for the 2.2 API Level 8 so that my applications run on API versions 2.2, 2.3.7, 3.0, 3.1, 3.2, 4.0, 4.0.4, and 4.1.2. Later versions are obviously backward compatible, so the further back you develop your minimum version level support, the more people will be able to use your application. If you want to make money selling Android apps, this concept translates directly into dollars, as there are millions of 2.2 and 2.3.7 devices still out there, including the original Amazon Kindle Fire which runs 2.3.7.

Creating Your First Android Application

By now, you’re probably aching to fire up Eclipse Juno 4.2 for Java EE and create an Android 4.1 application to see how all of this works together. A tradition in all programming languages for new users is the crafting of the “Hello World” application, so let’s create our own Hello Absolute Beginner application right here and now.

First, we’ll launch Eclipse and create the application. Then we’ll take a look at the files and Java and XML code that Eclipse generates to get your app up and running. Finally, we’ll give the app an icon to display on the Android device’s (smartphone, tablet, e-reader or iTV) main menu.

Launching Eclipse

The first step is to launch Eclipse Juno 4.2 for Java EE. From there, you’ll create an Android project to house the application code, markup, and assets.

To launch Eclipse, find and click the Eclipse shortcut launch icon on your workstation. If a security warning dialog like the one shown in Figure 4-3 appears, click Run. If you don’t want to see this dialog every time you start Eclipse, uncheck the box that reads “Always ask before opening this file.”

9781430247883_Fig04-03.jpg

Figure 4-3 .  The Windows security warning dialog for Eclipse Juno 4.2 for Java EE launch

Next you will see the Eclipse Juno startup screen. Then, in a few more seconds, a dialog will appear, allowing you to tell Eclipse where your projects folder is kept on your hard disk drive. I’m going to accept the default User Directory with my nickname, so the entry is C:UsersWallsworkspace, as shown in Figure 4-4. If you don’t want to specify this each time you start Eclipse, you can check the “Use this as the default and do not ask again” option. Once you click the OK button, Eclipse will start, and the IDE will appear.

9781430247883_Fig04-04.jpg

Figure 4-4 .  The Eclipse workspace location definition dialog

Creating an Android Project

  1. Once the IDE has launched, select File image New image Project in the Eclipse main menu to create a new project just like we did in Chapter 3 to see if Android Development Tools had installed correctly inside of Eclipse. This is shown in Figure 4-5 using two screenshots combined into one (to save space) the File image New image Project menu sequence as well as the resulting New Project Dialog.
  2. In the New Project dialog, open the Android folder using the arrow just to the left.
  3. Next, select Android Application Project from the list of wizards to tell Eclipse the type of project you wish to create, as shown on the right in Figure 4-5. Click the Next button to continue.

9781430247883_Fig04-05.jpg

Figure 4-5 .  The Eclipse 4.2 New image Project image Android Application Project menu sequence and dialog

Next you’ll see the New Android Application dialog, which allows you to specify all types of important variables for your applications. Let’s address them one by one.

  • Application Name: This is the name of the application and will be displayed on the top of the screen on the Android device. Let’s give this the same name as our Project name (note that the dialog does this for you as you type it in, entering it into both fields): HelloAbsoluteBeginner.

Caution  We have omitted spaces from the folder name because spaces are not supported in Java names. It is not advisable to use spaces in names of folders that you use for software development.

  • Project Name: This is the name of the folder in your C:UsersYourNameworkspace folder that holds your Hello Absolute Beginner application folders and files. Let’s give this folder the same name as our application: HelloAbsoluteBeginner
  • Package name: This is the name you want to use for your Java package. For now, we will simply define this as the name of the container that will hold all of the Java code our application uses. Let’s name this package first.example.helloabsolutebeginner. (Java package names are separated by periods, much like file pathnames are separated by back slashes.)
  • Build SDK: This panel allows you to specify the version of Android that your application will support. The more you support, the more users will be able to use your application, so usually we would use a build target of Android 1.6. That version has everything that we will need to build most applications that work across all current Android smartphones. For now, however, let’s just accept the default current API Level 16, which means we’re developing this first application to run on the current Android 4.1 Jelly Bean platform and 4.1 phone and tablet emulator we just installed in Chapter 3.
  • Minimum Required SDK: I am also going to accept the default Minimum Required SDK of API Level 8, which means your application will be compatible back to Android 2.2 smartphones and tablets, meaning users with Android 2.2, 2.3.7, 3.0, 3.1, 3.2, 4.0, 4.0.4, and 4.1 compatible hardware will be able to run the application.
  • Create Custom Launcher Icon: Leave this box selected so that we can see the dialog (next) that helps to automate creation of an App Icon for the Launch Area on your Android smartphone or tablet. We also will see how to create these icons manually later on in this chapter as well.
  • Create Project in Workspace: Leave this box selected as well so that Android will create the project folder structure for this application under your C:/Users/Name/workspace/ folder on your system’s hard disk drive.

Figure 4-6 shows the completed New Android Application dialog for this example. When you are finished filling it out, click the Next button.

9781430247883_Fig04-06.jpg

Figure 4-6 .  The New Android Application dialog for your HelloAbsoluteBeginner Android app

After you click the Next button in the New Android Application dialog, you will get the Configure Launcher Icon Dialog as shown in Figure 4-7. Because we haven’t created our Application Launch Icons as yet, just accept the default settings and click on the Next button to advance on into the new Android App project creation process.

9781430247883_Fig04-07.jpg

Figure 4-7 .  Accepting the Default Configure Launcher Icon Dialog settings

Next you will see the Create Activity Type Dialog shown in Figure 4-8 and for which we will be selecting a settings value of “Blank Activity,” so that we can create a Blank (basic) Activity and see the basic (minimum) code that the New Android App functionality in Eclipse will create for us automatically. This auto-code generation is just what we need right now as an absolute beginner, and as you will see Android Development Tools in Eclipse does a great job at giving new developers a head start by writing some of the basic application bootstrapping code for them! Let’s hit the Next button shown in Figure 4-8 and continue the New Android App project creation process to set the parameters for our Activity as shown in Figure 4-9.

9781430247883_Fig04-08.jpg

Figure 4-8 .  Creating a Blank Activity in the New Android Application series of dialogs

The New Blank Activity Dialog allows us to set the parameters for our apps activity, which is essentially the user interface or “front end” of our app that the users will use to control and utilize the app. Let’s use “HelloActivity” for our Activity Name and Title and “activity_hello” as our layout (user interface) name as shown in Figure 4-9. Leave the Navigation Type and Hierarchical Parent settings at their defaults for now, and let’s see how Android inserts our naming conventions into the Java code and XML markup for our app. Click on the Next button to continue the process.

9781430247883_Fig04-09.jpg

Figure 4-9 .  Filling out the parameters for our New Blank Activity in the New Android Application dialogs

Normally the New Android Application process would now create your New Android Project for you, but before it does so, it checks the state of your current Android Development Environment Installation (which we created in Chapter 3) to make sure that you have all of the SDKs, APIs, and so on that will be needed for the New Project you are specifying. In this case, Android found a missing API that would be needed to be installed for this Application to work (compile) properly, so it brings up the following dialog to let you know it needs something to be added to your current development environment. Again I am combining two screens into one in Figure 4-10 to show both the alert dialog and the repository search and fetch progress after you click the “Install/Update” button, to OK the addition of Android 2.2 support to your collection of SDKs and APIs. Make sure you are connected to the Internet before clicking the Install/Update button shown in Figure 4-10! Note that if your Android installation is 100% up to date that you will not get the Install Dependencies dialog and will not have to go through the process shown here in Figures 4-10 through 4-12.

9781430247883_Fig04-10.jpg

Figure 4-10 .  Installing/Upgrading Dependencies found to be needed by Android to support your application

After you click the Install/Upgrade button in the New Android Application dialog, and the necessary files are located and fetched from the repository, you will get the Choose Packages to Install Dialog as shown in Figure 4-11. Select the Accept All Radio Button as we have in the past and then click on the Install button to have the Froyo Android 2.2 API packages installed via your Internet connection.

9781430247883_Fig04-11.jpg

Figure 4-11 .  Accepting the suggested Packages to Install that are needed to support your New Android Application settings

After you click Install in the Choose Packages to Install dialog, you will get the progress bar dialog shown in Figure 4-12 showing you the speed and progress of your installation.

9781430247883_Fig04-12.jpg

Figure 4-12 .  Download Progress Bar for installing the Android Support Library needed for your application

Once the Android 2.2 API installations are complete you will be finished with the New Android Application Project Creation and returned to Eclipse where the IDE will now be populated with your new (empty) project ready for development!

Inspecting and Editing the Android Application Files

After you click Finish in the New Android Application dialog, you are returned to Eclipse. In the IDE, you can navigate through the new (empty) project structure using the Package Explorer pane.

Let’s look at the folder hierarchy that Eclipse has automatically created for our project. Click the arrow icons next to the HelloAbsoluteBeginner folder, and then click the arrow icons next to the src and res folders under it.

Going further, click the open folder arrows next to the first.example.helloabsolutebeginner, menu, layout, and values folders, so you can see the Java and XML files that Eclipse has so kindly created for us. Figure 4-13 shows the Package Explorer pane at this point.

9781430247883_Fig04-13.jpg

Figure 4-13 .  The Eclipse 4.2 IDE with Package Explorer pane and activity_hello.xml markup shown

Now let’s open some of these files and see just how much coding Eclipse has done for this project.

To open any of the files listed in the Package Explorer, select the file by clicking once on it (the icon will turn blue), and then press F3. Alternatively, right-click the file name to get a context-sensitive menu, and then select the Open option. You will see that the activity_hello.xml file is already open, to see the markup code click the activity_hello.xml tab at the bottom right of the center coding area of Eclipse as shown in Figure 4-13. A later screen will show the Graphical Layout view of this XML file.

Opening the HelloActivity.java Activity

The HelloActivity.java file holds our activity class. Right-click it and select Open to explore it now. As shown in Figure 4-14, Eclipse has already written the code to create a UI screen for the application and set its content to the UI defined in the activity_hello.xml file (with the R.layout.activity_hello text), which we will look at next.

9781430247883_Fig04-14.jpg

Figure 4-14 .  Our HelloActivity.java activity creation code shown in the Eclipse 4.2 IDE

Let’s examine this in a little more detail:

package first.example.helloabsolutebeginner;
 
import android.os.Bundle;
 
public class HelloActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_hello, menu);
        return true;
    }
}

As you can see, Eclipse used the information in our New Android Application Project dialog to create a usable Java file, which includes a first.example.helloabsolutebeginner package declaration, import statements, a HelloActivity activity class, and  onCreate() methods that create a layout (UI) and menu structure placeholder.  Also notice in Figure 4-14 that on the right of the Eclipse IDE a useful “Outline Pane,” which gives a bird’s-eye hierarchical overview of your java code, which will become more useful as your code becomes more complicated!

Opening the UI Definition

Next, let’s take a look at our UI (user interface) markup code in the activity_hello.xml file in the layout folder, as shown in Figure 4-13. The XML code in the activity_hello.xml file is quite a bit different from the Java code. To see it, click the activity_hello.xml tab at the bottom of the middle code editing pane or section of Eclipse, or see Figure 4-13.

<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="@string/hello_world"
    tools:context=".HelloActivity"
    />
</RelativeLayout>

XML uses tags similar to those used in HTML markup to define structures that you will be using in your applications. In this case, it is a UI structure that contains a RelativeLayout tag, which keeps our UI elements organized via relative layout positioning and a TextView tag, which allows us to put our text message on the application screen.

Note  If you don’t see something such as Figure 4-13 or Figure 4-15, to view the file, right-click its icon in the layout folder, select Open, and then choose activity_hello.xml at the bottom of the middle pane in the Eclipse window.

9781430247883_Fig04-15.jpg

Figure 4-15 .  The Graphical Layout Editor in Eclipse where our UI layout for our activity is created

Notice that the TextView tag uses an attribute called android:text, which is set equal to @string/hello_world. This is a reference to the strings.xml file, which we are going to look at next.

Opening the Strings Resource File

So far, we have looked at the Java code, which points to the activity_hello.xml file, which in turn points to the strings.xml file. Open that file now (right-click the file’s icon in the Package Explorer and select Open) it is located in the values folder underneath the resources folder (/res/values). The file will open in a third tab within the Eclipse IDE, as shown in Figure 4-16.

9781430247883_Fig04-16.jpg

Figure 4-16 .  The strings.xml file when it first opens showing the default values

When you open the strings.xml file, you will see that Eclipse has already added four variables: app_name, hello_world, menu_settings , and title_activity_hello. The string variable named hello_world is to hold the text that we want our application to display. The app_name variable is to hold the string data that will appear in the title bar at the top of the application. We already specified it in the New Android Application dialog as HelloAbsoluteBeginner.

Notice the tabs at the bottom of the editing pane labeled Resources and strings.xml. These tabs allow you to switch between the actual XML code and the more user-friendly interface that you see in Figure 4-16, which makes editing Android resources a bit easier than coding straight XML. Because we’re absolute beginners we’ll utilize these features to make our development work easier, at least for now.

Because the app_name value is already specified thanks to our New Android Application dialog, let’s leave it alone and set the value of hello_world to something new.

Setting a Variable Value in strings.xml

To set the value of hello_world, all you need to do is to click its name in the left pane of the Resources view and edit its text in the right pane of the Resources view. Once you click hello_world, two fields will appear. One contains the string variable name (hello_world), and the other has its value. In the Value field, type Hello Absolute Beginner!, as shown in Figure 4-17. This is the value (the text) that will appear on the screen of our App when we run it later on in this chapter.

9781430247883_Fig04-17.jpg

Figure 4-17 .  Editing the value of the hello_world String to display: Hello Absolute Beginner!

Once you have entered a new string value for the hello_world variable, click the strings.xml tab at the bottom of the editing pane, and take a look at the XML code that Eclipse has generated for you, as shown in Figure 4-18.

9781430247883_Fig04-18.jpg

Figure 4-18 .  The updated XML code for the strings.xml resource file as shown under the strings.xml tab

In this view, you can see the actual XML code for the string tags, which are nested inside the <resources> tags that allow us to define resources for our Android application.

<resources>
    <string name="app_name">HelloAbsoluteBeginner</string>
    <string name="hello_world">Hello Absolute Beginner!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_hello">HelloActivity</string>
</resources>

Each <string> tag has a variable name attribute so we can refer to it by name in our Java code. Tags end with the same tag that they started with, but they have an added forward slash, like this: < string> XXX</ string>.

As you can see in the XML code, Eclipse has created the correct XML code for us to use to write our Hello World message to the smartphone, tablet, e-reader, or iTV screen. The code reads as follows:

<string name="hello_world">Hello Absolute Beginner!</string>

Now it’s time to save the strings.xml file you just edited using the CTRL-S shortcut (File image Save) and then we can compile and run your first app, the Hello Absolute Beginner application.

Running the App

To compile and run the application, right-click the HelloWorldAndroid folder icon in the Eclipse Package Explorer and select Run As image Android Application as shown in Figure 4-19.

9781430247883_Fig04-19.jpg

Figure 4-19 .  Using the right-click (on Project Folder) Run As image Android Application menu sequence

The first thing Eclipse will do when you try to run your app is to make sure your files are all saved. If they are not, you will see a dialog like the one shown in Figure 4-20, which appears in this case because we modified the hello_world variable but did not hit the CTRL-S (Save) keystroke afterward that saves the file. Therefore, we’ll let Android Development Tools do it for us by clicking the “Yes” option in the dialog that asks us if we want to save the file before running the app.

9781430247883_Fig04-20.jpg

Figure 4-20 .  If you forgot to save your strings.xml file via CTRL-S then Eclipse will let you know about it

Eclipse will then compile your app, and will open a version 4.1 emulator window to display a virtual Android device (smartphone or tablet) representation (emulator) on which to run it. When the emulator first starts up, it will display the standard smartphone (or it could be a tablet) screen, simulating an Android OS background image and the standard Android icons for system time, signal strength, battery charge level, network type (3G, 4G, etc.) and so on. Note that it may take some time for the emulator to load into memory (especially the first time) and to load your app and run it once it is in memory.

The app should launch automatically once the emulator starts, but if for some reason it doesn’t, to actually run the app in the emulator, you may need to click the Menu button in the center-bottom area of the screen, or use the Home button to display your application icons and then select an icon to run. Usually your application will just run automatically, you just need to wait long enough for this to happen. You can also use the phone interface, finding and running the app as you would in real life because this is a test environment. Give it a shot now. Figure 4-21 shows the Hello Absolute Beginner App running in the Android 4.1 emulator.

9781430247883_Fig04-21.jpg

Figure 4-21 .  Running the Hello Absolute Beginner’s app in the Android 4.1 device emulator

After you exit the 4.1 Emulator for the first time by clicking the Red X at the top right of the window, you will probably get an “Auto Monitor Logcat” error dialog as shown in Figure 4-22, which suggests that you enable ADT to automatically monitor the Logcat output for messages (usually error messages) from the Android Applications run in the Emulator. Select the “Yes, Monitor Logcat” option, and click on the OK button to continue.

9781430247883_Fig04-22.jpg

Figure 4-22 .  Setting Android to monitor LogCat and display LogCat view in the Eclipse IDE

After you click OK you will be returned to Eclipse where you will see what no programmer or developer wants to see in his or her IDE—Red Ink! The red text at the bottom of the IDE In the Console tab will show feedback on the compile and run process, and in this case it related not to problems in our code but to the fact that the Logcat was not set up, which we rectified in our previous step by telling the ADT to set it up for us. You can see the Logcat error messages in Figure 4-23.

9781430247883_Fig04-23.jpg

Figure 4-23 .  Displaying where compiler and emulator errors appear in the Console Tab/Pane of the Eclipse IDE

To make sure that these error messages will go away once we have enabled the Logcat, let’s practice our right-click (on the project name) Run As image Android Application menu sequence again, and see if we can get some black text in the console window this time, which is what we want to see and represents feedback on what ADT is doing to compile and run your app each time you invoke this Run As Android App menu sequence. The results are shown in Figure 4-24.

9781430247883_Fig04-24.jpg

Figure 4-24 .  Displaying what a clean compile and emulator console feedback output should look like

Congratulations, you have created your first error-free Android 4.1 application. Next, we’ll customize its Android icon.

Adding an Application Icon

The final item that we are going to do in this chapter is give our application an icon that will show up on users’ Android devices and can be used by them to launch the application. We’ll use what you have learned about defining alternate resources by creating an icon that works on small, medium, large, and extra large screens. We’ll add the appropriate ic_launcher.png files into the correct alternate dpi resolution folders provided by our Android Application project we just created, so that Android automatically finds and uses the correct application launcher icon for each type of Android device screen size and density:

  • /res/drawable-ldpi for small low density dot per inch (LDPI) screens
  • /res/drawable-mdpi for average medium density dot per inch (MDPI) screens
  • /res/drawable-hdpi for large high density dot per inch (HDPI) screens
  • /res/drawable-xhdpi for extra large extra-high density dot per inch (XHDPI) screens

Not surprisingly, this is done by giving your icon an exact name and file format, and putting it into an exact directory. When Android finds an icon file there, it automatically puts it into play as your application’s icon. The files must follow these rules precisely:

  • Be placed in the correct /res/drawable-dpi folder, which holds all of the drawable resources for that screen resolution
  • Be named ic_launcher.png
  • Be a 24-bit PNG file with an alpha channel (transparency), also known as a 32-bit PNG, so that the icon overlays on any system background wallpaper seamlessly

Here, I’ll use my 3D company logo in an Android Green hue, but you can use any image that you like. Also, I will use open source GIMP 2.8 for this image editing example, because all readers will have it installed, but you can use any image-editing program you prefer, such as Photoshop CS6 or Corel Painter. So let’s fire up the GIMP 2.8 software package that we installed earlier in the book and prepare a 24-bit PNG file with transparency (alpha channel).

Adding Transparency

The first thing we need to do is to put the logo onto a transparency. Here are the steps to remove the white background from the logo

  1. Open the MindTaffyLogoAndroidGreen.gif logo file using the GIMP File image Open menu sequence. It is 200 × 200 pixels and the first frame of an Animated GIF file that is from my WallaceJackson.com website.

  2. Select the “Select By Color” tool (fifth in the toolbar) and set the tolerance at 15 (bottom middle tool tab for Select by Color tool settings) and the Select By setting to Composite. Make sure the Antialiasing option is checked as well and then click the white area to select it as shown in Figure 4-25.

9781430247883_Fig04-25.jpg

Figure 4-25 .  Selecting the white area in the image that will be our transparent icon to remove white values

  3. Right-click in the white area in the layers tab (upper-left in Figure 4-25), which is directly underneath the layer showing the MindTaffyLogoAndroidGreen.gif image that we opened in Step 1, and select the “New Layer” option to open the New Layer Dialog as shown in Figure 4-26. Name the new layer “Transparency,” and accept the other defaults as provided, and click OK.

9781430247883_Fig04-26.jpg

Figure 4-26 .  Naming the layer “Transparency” and setting its width, height, and fill type options

  4. Choose the Select Menu and then the Invert menu option shown in Figure 4-27 to invert the selected white areas. This will grab only the logo because before only the white (nonlogo) areas were selected and therefore after the Invert operation only the logo pixels (nonwhite area) will be selected. Pretty cool.

9781430247883_Fig04-27.jpg

Figure 4-27 .  Using a Select image Invert menu sequence to select the logo portion of the image rather than the white

  5. Next select the Edit Menu image Copy Option shown in Figure 4-28 to copy this selected logo image data to the clipboard. Note that in GIMP when you have your mouse over a menu or option it tells you exactly what it will do, and I have included these in the screens in this chapter to make it even easier to follow along.

9781430247883_Fig04-28.jpg

Figure 4-28 .  Using the Edit image Copy menu sequence to copy the selected logo data to the clipboard (memory)

  6. Click on your Transparency Layer on the left to select it (the layer will turn blue) if it isn’t selected already, and then hit the CTRL-V keystroke combination to paste the pixel data from the clipboard, or you can use the Edit Menu image Paste Option if you want a more visual work process. Next, click on the Eye Icon (turns layer visibility on or off) next to the original MindTaffyLogoAndroidGreen.gif layer at the bottom of the layer stack, so all that is showing in your preview on the right is the transparency layer and the floating selection (the logo only pixels), which you just pasted. The result of this work process are shown in Figure 4-29. Transparency in GIMP (and Photoshop for that matter) is represented by a checkerboard pattern, in case you are wondering!

9781430247883_Fig04-29.jpg

Figure 4-29 .  Pasting the Logo (icon) data onto the transparency layer and turning off visibility of original art

  7. Now that we have the Launcher Icon image in the transparent format needed to “composite” it (blend it seamlessly) with any Android desktop out there, we will use the Image Menu’s Scale Image Option, shown in Figure 4-30, to turn this 200 by 200 pixel image into the target icon image sizes (96, 72, 48, and 36 pixels) that we will need for our four Drawable Resources Folders.

9781430247883_Fig04-30.jpg

Figure 4-30 .  Using the Image image Scale Image… menu sequence to scale the image to target icon resolutions

The Scale Image dialog shown in Figure 4-31 allows us to specify what image size we wish to scale our image down to, in this case 96 pixels for our /drawable-xhdpi/ folder location, and to also choose an Interpolation Algorithm, in this case “Cubic” (known as “Bi-Cubic” in Photoshop) interpolation, which yields the highest quality level, as you will see. Once you set your scaling parameters, click the “Scale” button to commit the scaling operation, and scale your 200 pixel image into a 96 pixel extra high density Android device icon!

9781430247883_Fig04-31.jpg

Figure 4-31 .  Setting the Scale Image parameters to 96 by 96 pixel for XHDPI icon requirements

Next we will select the File Menu image Export Option shown in Figure 4-32. Also note that our transparent icon is now at the required 96 by 96 pixel size.

9781430247883_Fig04-32.jpg

Figure 4-32 .  Using the File image Export menu sequence to export our 96 pixel XHDPI icon

In the File Export dialog, use the Places Navigator Pane on the left to find your workspace folder and the HelloAbsoluteBeginner project folder and drawable-xhdpi target folder as shown in Figure 4-33. Click on the ic_launcher.png file that was auto-created for us previously to select that file for replacement with our new custom icon. The filename will be placed automatically in the top Name field for you when you do this, and the Save in Folder field will also have the proper path to your drawable-xhdpi folder from your C: drive! Once everything is configured correctly, click on the “Export” button to over write your custom XHDPI icon and replace the generic one that was auto-created for us earlier.

9781430247883_Fig04-33.jpg

Figure 4-33 .  Exporting our ic_launcher.png file to the workspace project resource drawable XHDPI folder

Once you click on Export you will get two dialogs as shown in Figure 4-34, the first confirming that you want to replace (overwrite) the existing ic_launcher.png launcher icon, and the second requesting File Export settings that pertain to the PNG file format.

9781430247883_Fig04-34.jpg

Figure 4-34 .  Confirming the replacement of the original icon and settings for the PNG32 file format

To create the other three resolution icons, rather than going through the entire work process outlined earlier, let’s take a clever shortcut that involves the Edit Menu image Undo Option shown in Figure 4-35 to save a dozen steps of work! All we need to do is use the Edit image Undo Scale and redo the last couple of steps (Image Scale and File Export) and then do the same work process to scale the 200 pixel transparent image to 72, 48, and 36 pixels and then File image Export to the HDPI, MDPI, and LDPI drawable folders under your project file, replacing the ic_launcher.png file in each folder with its required resolution equivalent. Make sure to scale from the 200 pixel image each time (i.e., 200 pixels scale to 72 pixels, 200 pixels scale to 48 pixels, and 200 pixels scaled to 36 pixels) as the quality result will be significantly better than if you used a work process in which you scaled from 200 to 96 and then 96 to 72, 72 to 48, and 48 to 36. This is because the more data you give the original Image Scaling Algorithm the better job it will do (the more it will have to work with) giving you a great result, so if you want to design your Launcher Icons at 864 pixels (which is what Google recommends in their graphics design guidelines) then by all means go for it!

9781430247883_Fig04-35.jpg

Figure 4-35 .  Undo the 200 pixel to 96 pixel scale operation so we can scale to other sizes

Summary

Android is very particular about which types of files you use and where you put them in your project folder. We will be looking at the particulars of how things need to be set up to work properly in Android throughout the rest of this book.

In this chapter, you created and compiled your first project for Android inside Eclipse using the Android application development environment you installed in Chapter 3. You saw that the Android Development Environment in Eclipse gives you a lot of development assistance, and as a beginner, you’ll want to take advantage of every bit of help you can get. The proof is in the pudding, as they say.

You just developed your first Android Hello Absolute Beginner application and needed to change only a single line of code in the Eclipse for Java EE IDE. You saw how Android sets up a basic application file and directory structure, and which Java and XML files are needed to create a UI, a menu, and a basic application. You saw how to Compile and Run your app in the Android 4.1 Device Emulator using the Run as Android Application command.

Your Android application icon is very important to the branding of your application, as it represents your application on the users’ desktop, which is usually crowded with all of the other installed application icons. Customizing your own app icon is as simple as creating the PNG32 graphics and then putting the icon files into their correct target resolution (DPI) folders. You just must make sure that the icon is saved in the correct file type, is the correct resolution, uses an alpha channel, and has the correct file name: ic_launcher.png.

The next chapter provides an overview of Java and how Android compartmentalizes things having to do with an application. In the remaining chapters, we will get down to actually coding in Java and creating XML markup that delivers your application’s UI and functionality in more advanced ways and with more advanced features.

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

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