Chapter 2

First Steps with the Android SDK

The Android SDK provides a set of tools that enables you to create applications in a short amount of time. This chapter will guide you through the process of building a simple Android application with the SDK tools. This involves the following steps:

  1. Setting up the development environment.
  2. Creating a new project in Eclipse and writing your code.
  3. Running the application on the emulator or on a device.
  4. Debugging and profiling the application.

We’ll conclude this chapter by looking into useful third-party tools. Let’s start with setting up the development environment.

Setting Up the Development Environment

The Android SDK is flexible, and it integrates well with several development environments. Purists might choose to go hard core with command-line tools. We want things to be a little bit more comfortable, though, so we’ll go for the simpler, more visual route using an IDE (integrated development environment).

Here’s the list of software you’ll need to download and install in the given order:

  1. The Java Development Kit (JDK), version 5 or 6. We suggest using 6. At the time of writing, JDK 7 is problematic in connection with Android development. One has to instruct the compiler to compile for Java 6.
  2. The Android Software Development Kit (Android SDK).
  3. Eclipse for Java Developers, version 3.4 or newer.
  4. The Android Development Tools (ADT) plug-in for Eclipse.

Let’s go through the steps required to set up everything properly.

Note   As the Web is a moving target, we don’t provide specific download URLs here. Fire up your favorite search engine and find the appropriate places to get the items listed above.

Setting Up the JDK

Download the JDK with one of the specified versions for your operating system. On most systems, the JDK comes in an installer or package, so there shouldn’t be any hurdles. Once you have installed the JDK, you should add a new environment variable called JDK_HOME pointing to the root directory of the JDK installation. Additionally, you should add the $JDK_HOME/bin (%JDK_HOME%in on Windows) directory to your PATH environment variable.

Setting Up the Android SDK

The Android SDK is also available for the three mainstream desktop operating systems. Choose the version for your platform and download it. The SDK comes in the form of a ZIP or tar gzip file. Just uncompress it to a convenient folder (for example, c:android-sdk on Windows or /opt/android-sdk on Linux). The SDK comes with several command-line utilities located in the tools/ folder. Create an environment variable called ANDROID_HOME pointing to the root directory of the SDK installation, and add $ANDROID_HOME/tools (%ANDROID_HOME% ools on Windows) to your PATH environment variable. This way you can easily invoke the command-line tools from a shell later on if the need arises.

Note   For Windows you can also download a proper installer that will set up things for you.

After performing the preceding steps, you’ll have a bare-bones installation that consists of the basic command-line tools needed to create, compile, and deploy Android projects, as well as the SDK Manager, a tool for installing SDK components, and the AVD Manager, responsible for creating virtual devices used by the emulator. These tools alone are not sufficient to start developing, so you need to install additional components. That’s where the SDK manager comes in. The manager is a package manager, much like the package management tools you find on Linux. The manager allows you to install the following types of components:

  • Android platforms: For every official Android release, there’s a platform component for the SDK that includes the runtime libraries, a system image used by the emulator, and any version-specific tools.
  • SDK add-ons: Add-ons are usually external libraries and tools that are not specific to a platform. Some examples are the Google APIs that allow you to integrate Google Maps in your application.
  • USB driver for Windows: This driver is necessary for running and debugging your application on a physical device on Windows. On Mac OS X and Linux, you don’t need a special driver.
  • Samples: For each platform, there’s also a set of platform-specific samples. These are great resources for seeing how to achieve specific goals with the Android runtime library.
  • Documentation: This is a local copy of the documentation for the latest Android framework API.

Being the greedy developers we are, we want to install all of these components to have the full set of this functionality at our disposal. Thus, first we have to start the SDK manager. On Windows, there’s an executable called SDK manager.exe in the root directory of the SDK. On Linux and Mac OS X, you simply start the script android in the tools directory of the SDK.

Upon first startup, the SDK manager will connect to the package server and fetch a list of available packages. The manager will then present you with the dialog shown in Figure 2-1, which allows you to install individual packages. Simply click the New link next to Select, and then click the Install button. You’ll be presented with a dialog that asks you to acknowledge the installation. Check the Accept All check box, and then click the Install button again. Next, make yourself a nice cup of tea or coffee. The manager will take a while to install all the packages. The installer might ask you to provide login credentials for certain packages. You can safely ignore those and just click Cancel.

9781430246770_Fig02-01.jpg

Figure 2-1.  First contact with the SDK manager

You can use the SDK manager at anytime to update components or install new ones. Once the installation process is finished, you can move on to the next step in setting up your development environment.

Installing Eclipse

Eclipse comes in several different flavors. For Android developers, we suggest using Eclipse for Java Developers version 3.7.2, code named “Indigo.” Similar to the Android SDK, Eclipse comes in the form of a ZIP or tar gzip package. Simply extract it to a folder of your choice. Once the package is uncompressed, you can create a shortcut on your desktop to the eclipse executable in the root directory of your Eclipse installation.

The first time you start Eclipse, you will be prompted to specify a workspace directory. Figure 2-2 shows you the dialog.

9781430246770_Fig02-02.jpg

Figure 2-2.  Choosing a workspace

A workspace is Eclipse’s notion of a folder containing a set of projects. Whether you use a single workspace for all your projects or multiple workspaces that group just a few projects is completely up to you. The sample projects that accompany this book are all organized in a single workspace, which you could specify in this dialog. For now, we’ll simply create an empty workspace somewhere.

Eclipse will then greet you with a welcome screen, which you can safely ignore and close. This will leave you with the default Eclipse Java perspective. You’ll get to know Eclipse a little better in a later section. For now, having it running is sufficient.

Installing the ADT Eclipse Plug-In

The last piece in our setup puzzle is installing the ADT Eclipse plug-in. Eclipse is based on a plug-in architecture used to extend its capabilities by third-party plug-ins. The ADT plug-in marries the tools found in the Android SDK with the powers of Eclipse. With this combination, we can completely forget about invoking all the command-line Android SDK tools; the ADT plug-in integrates them transparently into our Eclipse workflow.

Installing plug-ins for Eclipse can be done either manually, by dropping the contents of a plug-in ZIP file into the plug-ins folder of Eclipse, or via the Eclipse plug-in manager integrated with Eclipse. Here we’ll choose the second route:

  1. Go to Help image Install New Software, which opens the installation dialog. In this dialog, you can choose the source from which to install a plug-in. First, you have to add the plug-in repository from the ADT plug-in that is fetched. Click the Add button. You will be presented with the dialog shown in Figure 2-3.

    9781430246770_Fig02-03.jpg

    Figure 2-3.  Adding a repository

  2. In the first text field, enter the name of the repository; something like “ADT repository” will do. The second text field specifies the URL of the repository. For the ADT plug-in, this field should be https://dl-ssl.google.com/android/eclipse/. Note that this URL might be different for newer versions, so check the ADT Plugin site for an up-to-date link.
  3. Click OK, and you’ll be brought back to the installation dialog, which should now be fetching the list of available plug-ins in the repository. Check the Developer Tools check box and click the Next button.
  4. Eclipse calculates all the necessary dependencies, and then presents to you a new dialog that lists all the plug-ins and dependencies that are going to be installed. Confirm by clicking the Next button.
  5. Another dialog pops up prompting you to accept the license for each plug-in to be installed. You should, of course, accept those licenses and then initiate the installation by clicking the Finish button.

    Note   During the installation, you will be asked to confirm the installation of unsigned software. Don’t worry, the plug-ins simply do not have a verified signature. Agree to the installation to continue the process.

  6. Eclipse asks you whether it should restart to apply the changes. You can opt for a full restart or for applying the changes without a restart. To play it safe, choose Restart Now, which will restart Eclipse as expected.

After Eclipse restarts, you’ll be presented with the same Eclipse window as before. The toolbar features several new buttons specific to Android, which allow you to start the SDK and AVD Managers directly from within Eclipse as well as create new Android projects. Figure 2-4 shows the new toolbar buttons.

9781430246770_Fig02-04.jpg

Figure 2-4.  ADT toolbar buttons

The first two buttons on the left allow you to open the SDK Manager and the AVD Manager, respectively. The button that looks like a check box lets you run Android lint, which checks your project for potential bugs. The next button is the New Android App Project button, a shortcut to create a new Android project. The rightmost two buttons, respectively, enable you to create a new unit test project or Android manifest file (functionality that we won’t use in this book).

As one last step in finishing the installation of the ADT plug-in, you have to tell the plug-in where the Android SDK is located:

  1. Open Window image Preferences and select Android in the tree view in the dialog that appears.
  2. On the right side, click the Browse button to choose the root directory of your Android SDK installation.
  3. Click the OK button to close the dialog. Now you’ll be able to create your first Android application.

A Quick Tour of Eclipse

Eclipse is an open source IDE you can use to develop applications written in various languages. Usually, Eclipse is used in connection with Java development. Given Eclipse’s plug-in architecture, many extensions have been created, so it is also possible to develop pure C/C++, Scala, or Python projects as well. The possibilities are endless; even plug-ins to write LaTeX projects exist, for example—something that only slightly resembles your usual code development tasks.

An instance of Eclipse works with a workspace that holds one or more projects. Previously, we defined a workspace at startup. All new projects you create will be stored in the workspace directory, along with a configuration that defines the look of Eclipse when using the workspace, among other things.

The user interface (UI) of Eclipse revolves around two concepts:

  • A view, a single UI component such as a source code editor, an output console, or a project explorer.
  • A perspective, a set of specific views that you’ll most likely need for a specific development task, such as editing and browsing source code, debugging, profiling, synchronizing with a version control repository, and so on.

Eclipse for Java Developers comes with several predefined perspectives. The ones in which we are most interested are called Java and Debug. The Java perspective is the one shown in Figure 2-5. It features the Package Explorer view on the left side, a Source Code view in the middle (it’s empty, as we didn’t open a source file yet), a Task List view to the right, an Outline view, and a tabbed view that contains subviews called Problems view, Javadoc view, Declaration view, and Console view.

9781430246770_Fig02-05.jpg

Figure 2-5.  Eclipse in action—the Java perspective

You are free to rearrange the location of any view within a perspective via drag and drop. You can also resize views. Additionally, you can add and remove views to and from a perspective. To add a view, go to Window image Show View, and either select one from the list presented or choose Other to get a list of all available views.

To switch to another perspective, you can go to Window image Open Perspective and choose the one you want. A faster way to switch between already open perspectives is given to you in the top-left corner of Eclipse. There you will see which perspectives are already open and which perspective is active. In Figure 2-5, notice that the Java perspective is open and active. It’s the only currently open perspective. Once you open additional perspectives, they will also show up in that part of the UI.

The toolbars shown in Figure 2-5 are also just views. Depending on the perspective you are in at the time, the toolbars may change as well. Recall that several new buttons appeared in the toolbar after we installed the ADT plug-in. This is a common behavior of plug-ins: they will, in general, add new views and perspectives. In the case of the ADT plug-in, we can now also access a perspective called DDMS (Dalvik Debugging Monitor Server, which is specific to debugging and profiling Android applications, as covered later in the chapter) in addition to the standard Java Debug perspective. The ADT plug-in also adds several new views, including the LogCat view, which displays the live logging information from any attached device or emulator.

Once you get comfortable with the perspective and view concepts, Eclipse is a lot less intimidating. In the following subsections, we will explore some of the perspectives and views we’ll use to write Android games. We can’t possibly cover all the details of developing with Eclipse, as it is such a huge beast. We therefore advise you to learn more about Eclipse via its extensive help system if the need arises.

Helpful Eclipse Shortcuts

Every new IDE requires some time to learn and become accustomed to. After using Eclipse for many years, we have found the following shortcuts speed up software development significantly. These shortcuts use Windows terms, so Mac OS X users should substitute Command and Option where appropriate:

  • Ctr + Shift + G with the cursor on a function or field will perform a workspace search for all references to the function or field. For instance, if you want to see where a certain function is called, just click to move the cursor onto the function and press Ctrl + Shift + G.
  • F3 with the cursor on a calling into function will follow that call and bring you to the source code that declares and defines the function. Use this hotkey in combination with Ctrl + Shift + G for easy Java source code navigation. Doing the same on a class name or a field will open up its declaration.
  • Ctr + spacebar autocompletes the function or field name you are currently typing. Start typing and press the shortcut after you have entered a few characters. When there are multiple possibilities, a box will appear.
  • Ctr + Z is undo.
  • Ctr + X cuts.
  • Ctr + C copies.
  • Ctr + V pastes.
  • Ctr + F11 runs the application.
  • F11 debugs the application.
  • Ctr + Shift + O organizes the Java imports of the current source file.
  • Ctr + Shift + F formats the current source file.
  • Ctr + Shift + T jumps to any Java class.
  • Ctr + Shift + R jumps to any resource file; that is, an image, a text file, and so on.
  • Alt + Shift + T brings up the refactor menu for the current selection.
  • Ctrl + O lets you jump to any method or field in the currently open Java class.

There are many more useful features in Eclipse, but mastering these basic keyboard shortcuts can significantly speed up your game development and make life in Eclipse just a little better. Eclipse is also very configurable. Any of these keyboard shortcuts can be reassigned to different keys in the Preferences.

Creating a New Project in Eclipse and Writing Your Code

With our development set up, we can now create our first Android project in Eclipse. The ADT plug-in installed several wizards that make creating new Android projects very easy.

Creating the Project

There are two ways to create a new Android project. The first is to right-click in the Package Explorer view (see Figure 2-5) and then select New image Project from the pop-up menu. In the New dialog, select Android Project under the Android category. As you can see, there are many other options for project creation in that dialog. This is the standard way to create a new project of any type in Eclipse. After you click OK in the dialog, the Android project wizard opens.

The second way is a lot easier: just click the New Android App Project toolbar button (shown earlier in Figure 2-4), which also opens the wizard.

Once you are in the Android project wizard dialog, you have to make a few decisions. Follow these steps:

  1. Define the application name. This is the name shown in the launcher on Android. We’ll use “Hello World.”
  2. Specify the project name. This is the name your project will be referred by in Eclipse. It is customary to use all lowercase letters, so we’ll enter “helloworld.”
  3. Specify the package name. This is the name of the package under which all your Java code will live. The wizard tries to guesstimate your package name based on your project name, but feel free to modify it to your needs. We’ll use “com.helloworld” in this example.
  4. Specify the build SDK. Select Android 4.1. This allows us to use the latest APIs.
  5. Specify the minimum required SDK. This is the lowest Android version your application will support. We’ll choose Android 1.5 (Cupcake, API level 3).

    Note   In Chapter 1, you saw that each new release of Android adds new classes to the Android framework API. The build SDK specifies which version of this API you want to use in your application. For example, if you choose the Android 4.1 build SDK, you get access to the latest and greatest API features. This comes at a risk, though: if your application is run on a device that uses a lower API version (say, a device running Android version 1.5), then your application will crash if you access API features that are available only in version 4.1. In this case, you’d need to detect the supported SDK version during runtime and access only the 4.1 features when you’re sure that the Android version on the device supports this version. This may sound pretty nasty, but as you’ll see in Chapter 5, given a good application architecture, you can easily enable and disable certain version-specific features without running the risk of crashing.

  6. Click Next. You’ll be shown a dialog that lets you define your application’s icon. We’ll keep everything as is, so just click Next.
  7. In the next dialog, you are asked whether you want to create a blank activity. Accept this choice and move on by clicking Next.
  8. In the final dialog, you can modify some attributes of the blank activity the wizard will create for you. We set the activity name to “HelloWorldActivity” and the title to “Hello World.” Clicking Finish will create your first Android project.

Note   Setting the required minimum SDK version has some implications. The application can be run only on devices with an Android version equal to or greater than the minimum SDK version you specify. When a user browses Google Play via the Google Play application, only applications with the appropriate minimum SDK version will be displayed.

Exploring the Project

In the Package Explorer, you should now see a project called “helloworld.” If you expand it and all its children, you’ll see something like Figure 2-6. This is the general structure of most Android projects. Let’s explore it a little bit.

  • src/ contains all your Java source files. Notice that the package has the same name as the one you specified in the Android project wizard.
  • gen/ contains Java source files generated by the Android build system. You shouldn’t modify them, as they get regenerated automatically.
  • Android 4.1 tells us that we are building against an Android version 4.1 target. This is actually a dependency in the form of a standard JAR file that holds the classes of the Android 4.1 API.
  • Android Dependencies shows us any support libraries our application links to, again in form of JAR files. As game developers we are not concerned with these.
  • assets/ is where you store files your application needs (such as configuration files, audio files, and the like). These files get packaged with your Android application.
  • bin/ holds the compiled code ready for deployment to a device or emulator. As with the gen/ folder, we usually don’t care what happens in this folder.
  • libs/ holds any additional JAR files that we want our application to depend on. It also contains native shared libraries if our application uses C/C++ code. We’ll look into this in chapter 13.
  • res/ holds resources your application needs, such as icons, strings for internationalization, and UI layouts defined via XML. Like assets, the resources also get packaged with your application.
  • AndroidManifest.xml describes your application. It defines what activities and services comprise your application, what minimum and target Android version your application runs on (hypothetically), and what permissions it needs (for example, access to the SD card or networking).
  • project.properties and proguard-project.txt hold various settings for the build system. We won’t touch upon this, as the ADT plug-in will take care of modifying these files when necessary.

9781430246770_Fig02-06.jpg

Figure 2-6.  Hello World project structure

We can easily add new source files, folders, and other resources in the Package Explorer view by right-clicking the folder in which we want to put the new resources and selecting New plus the corresponding resource type we want to create. For now, though, we’ll leave everything as is. Next, let’s look into modifying our basic application setup and configuration so it is compatible with as many Android versions and devices as possible.

Making the Application Compatible with All Android Versions

Previously we created a project specifying Android 1.5 as our minimum SDK. Sadly, the ADT plug-in has a minor bug where it forgets to create the folder that houses the icon image for our application on Android 1.5. Here’s how we fix that:

  1. Create a folder in the res/ directory called drawable/. You can do this directly in the Package Explorer view by right-clicking the res/ directory and chose New image Folder from the context menu.
  2. Copy the ic_launcher.png file from the res/drawable-mdpi/ folder to the new assets/drawable/ folder. This folder is required for Android 1.5, whereas higher versions look for icons and other application resources in the other folders, based on their screen size and resolution. We’ll talk about this in Chapter 4.

With these changes, your application can run on all the Android versions that are currently out in the wild!

Writing the Application Code

We still haven’t written a single line of code, so let’s change that. The Android project wizard created a template activity class for us called HelloWorldActivity, which will get displayed when we run the application on the emulator or a device. Open the source of the class by double-clicking the file in the Package Explorer view. We’ll replace that template code with the code in Listing 2-1.

Listing 2-1. HelloWorldActivity.java

package com.helloworld;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class HelloWorldActivity extends Activity
                                implements View.OnClickListener {
    Button button;
    int touchCount;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super .onCreate(savedInstanceState);
        button = new Button( this );
        button.setText( "Touch me!" );
        button.setOnClickListener( this );
        setContentView(button);
    }
 
    public void onClick(View v) {
        touchCount++;
        button.setText("Touched me " + touchCount + " time(s)");
    }
}

Let’s dissect Listing 2-1, so you can understand what it’s doing. We’ll leave the nitty-gritty details for later chapters. All we want is to get a sense of what’s happening.

The source code file starts with the standard Java package declaration and several imports. Most Android framework classes are located in the android package.

package com.helloworld;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

Next, we define our HelloWorldActivity, and let it extend the base class Activity, which is provided by the Android framework API. An Activity is a lot like a window in classical desktop UIs, with the constraint that the Activity always fills the complete screen (except for the notification bar at the top of the Android UI). Additionally, we let the Activity implement the interface OnClickListener. If you have experience with other UI toolkits, you’ll probably see what’s coming next. More on that in a second.

public class HelloWorldActivity extends Activity
                                implements View.OnClickListener {

We let our Activity have two members: a Button and an int that counts how often the Button is touched.

    Button button;
    int touchCount;

Every Activity subclass must implement the abstract method Activity.onCreate(), which gets called once by the Android system when the Activity is first started. This replaces a constructor you’d normally expect to use to create an instance of a class. It is mandatory to call the base class onCreate() method as the first statement in the method body.

    @Override
    public void onCreate(Bundle savedInstanceState) {
           super .onCreate(savedInstanceState);

Next, we create a Button and set its initial text. Button is one of the many widgets that the Android framework API provides. UI widgets are called views on Android. Note that button is a member of our HelloWorldActivity class. We’ll need a reference to it later on.

        button = new Button( this );
        button.setText( "Touch me!" );

The next line in onCreate() sets the OnClickListener of the Button. OnClickListener is a callback interface with a single method, OnClickListener.onClick(), which gets called when the Button is clicked. We want to be notified of clicks, so we let our HelloWorldActivity implement that interface and register it as the OnClickListener of the Button.

        button.setOnClickListener( this );

The last line in the onCreate() method sets the Button as the content View of our Activity. Views can be nested, and the content View of the Activity is the root of this hierarchy. In our case, we simply set the Button as the View to be displayed by the Activity. For simplicity’s sake, we won’t get into details of how the Activity will be laid out given this content View.

        setContentView(button);
    }

The next step is simply the implementation of the OnClickListener.onClick() method, which the interface requires of our Activity. This method gets called each time the Button is clicked. In this method, we increase the touchCount counter and set the Button’s text to a new string.

    public void onClick(View v) {
        touchCount++;
        button.setText("Touched me" + touchCount + "times");
    }

Thus, to summarize our Hello World application, we construct an Activity with a Button. Each time the Button is clicked, we set its text accordingly. This may not be the most exciting application on the planet, but it will do for further demonstration purposes.

Note that we never had to compile anything manually. The ADT plug-in, together with Eclipse, will recompile the project every time we add, modify, or delete a source file or resource. The result of this compilation process is an APK file ready to be deployed to the emulator or an Android device. The APK file is located in the bin/ folder of the project.

You’ll use this application in the following sections to learn how to run and debug Android applications on emulator instances and on devices.

Running the Application on a Device or Emulator

Once we’ve written the first iteration of our application code, we want to run and test it to identify potential problems or just be amazed at its glory. We have two ways we can achieve this:

  • We can run our application on a real device connected to the development PC via USB.
  • We can fire up the emulator included in the SDK and test our application there.

In both cases, we have to do a little bit of setup work before we can finally see our application in action.

Connecting a Device

Before we can connect our device for testing purposes, we have to make sure that it is recognized by the operating system. On Windows, this involves installing the appropriate driver, which is part of the SDK we installed earlier. Just connect your device and follow the standard driver installation project for Windows, pointing the process to the driver/ folder in your SDK installation’s root directory. For some devices, you might have to get the driver from the manufacturer’s website. Many devices can use the Android ADB drivers that come with the SDK; however, a process is often required to add the specific device hardware ID to the INF file. A quick Google search for the device name and “Windows ADB” will often get you the information you need to get connected with that specific device.

On Linux and Mac OS X, you usually don’t need to install any drivers, as they come with the operating system. Depending on your Linux flavor, you might have to fiddle with your USB device discovery a little bit, usually in the form of creating a new rules file for udev. This varies from device to device. A quick Web search should bring up a solution for your device.

Creating an Android Virtual Device

The SDK comes with an emulator that will run Android Virtual Devices (AVDs). An Android Virtual Device consists of a system image of a specific Android version, a skin, and a set of attributes, which include the screen resolution, SD-card size, and so on.

To create an AVD, you have to fire up the Android Virtual Device Manager. You can do this either as described previously in the SDK installation step or directly from within Eclipse by clicking the AVD Manager button in the toolbar. You could use one of the already available AVDs. Instead, let’s walk through the steps of creating a custom AVD:

  1. Click the New button on the right side of the AVD Manager screen, which opens the Edit Android Virtual Device (AVD) dialog, shown in Figure 2-7.

    9781430246770_Fig02-07.jpg

    Figure 2-7.  Edit Android Virtual Device (AVD) dialog

  2. Each AVD has a name by which you can refer to it later on. You are free to choose any name you want.
  3. The target specifies the Android version that the AVD should use. For our simple “hello world” project, you can select an Android 4.0.3 target.
  4. The CPU/ABI specifies which CPU type the AVD should emulate. Select ARM here.
  5. You can specify the size of the SD card of the AVD, as well as the screen size via the options in the Skin settings. Leave those fields as is. For real-life testing, you’d usually want to create multiple AVDs that cover all the Android versions and screen sizes you want your application to handle.
  6. Enabling the snapshot option will save the state of the emulator when you close. Upon next startup, the emulator will load the snapshot of the saved stated instead of booting. This can save you some time when starting up a new emulator instance.
  7. Hardware options are more advanced. We’ll peek into a few in the next section. They let you modify low-level properties of the emulator devices and the emulator itself, such as whether the emulator’s graphics output should be hardware accelerated.

Note   Unless you have dozens of different devices with different Android versions and screen sizes, you should use the emulator for additional testing of Android version/screen size combinations.

Installing Advanced Emulator Features

There are a few hardware virtualization implementations that now support the Android emulator, Intel being one of them. If you have an Intel CPU, you should be able to install the Intel Hardware Accelerated Execution Manager (HAXM), which, in conjunction with an x86 emulator image, will virtualize your CPU and run significantly faster than a normal fully emulated image. Run in conjunction with this, enabling GPU acceleration will (in theory) provide a reasonable performance testing environment. Our experience with these tools in their current state is that they are still a bit buggy, but things look promising, so make sure to watch for official announcements from Google. In the meantime, let’s get set up:

  1. Download and install the HAXM software from Intel, available at http://software.intel.com/en-us/articles/intel-hardware-accelerated-execution-manager/.
  2. Once installed, you will need to make sure you have installed the specific AVD called Intel x86 Atom System Image. Open the SDK Manager, navigate to the Android 4.0.3 section, and check if the image is installed (see Figure 2-8). If it is not installed, check the entry, then click “Install packages . . .”

    9781430246770_Fig02-08.jpg

    Figure 2-8.  Selecting the x86 Atom System Image for ICS

  3. Create a specific AVD for the x86 image. Follow the steps to create a new AVD described in the last section, but this time make sure to select the Intel Atom (x86) CPU. In the Hardware section, add a new property called GPU emulation and set its value to yes, as shown in Figure 2-9.

    9781430246770_Fig02-09.jpg

    Figure 2-9.  Creating the x86 AVD with GPU emulation enabled

Now that you are armed with your new emulator image, we need to let you in on a few caveats. While testing, we had some mixed results. The image in Figure 2-10 is from a 2D game that uses OpenGL 1.1 multitexturing to get a subtle lighting effect on the characters. If you look closely at this image, you’ll see that the enemy faces are sideways and upside down. Proper rendering always has them right-side up, so that’s definitely a bug. Another, more complex game simply crashed and wouldn’t run. This isn’t to say the hardware accelerated AVD is not useful, because for more basic rendering, it may work just fine, and if you notice the number 61 in the bottom-right corner, that basically means it’s running 60 frames per second (FPS)—a new record for GL on the Android emulator on this test PC!

9781430246770_Fig02-10.jpg

Figure 2-10.  Fast OpenGL ES 1.1 emulation but with some rendering errors

The image in Figure 2-11 shows the main screen from a demo running OpenGL ES 2.0. While the demo rendered correctly, the frame rate started mediocre and ended up pretty bad. There’s not a whole lot being rendered in this menu and it’s already down to 45FPS. The main demo game ran at 15 to 30FPS, and it is also incredibly simple. It’s great to see ES 2.0 running, but clearly there is some room for improvement.

9781430246770_Fig02-11.jpg

Figure 2-11.  OpenGL ES 2.0 working, but with a lower frame rate

Despite the issues we’ve outlined in this section, the new emulator acceleration is a welcome addition to the Android SDK and we recommend trying it out for your game if you choose not to test exclusively on a device. There are many instances where it will work well, and you’ll likely find that you have faster turnaround times testing, which is what it’s all about.

Running an Application

Now that you’ve set up your devices and AVDs, you can finally run the Hello World application. You can easily do this in Eclipse by right-clicking the “hello world” project in the Package Explorer view and then selecting Run As image Android Application (or you can click the Run button on the toolbar). Eclipse will then perform the following steps in the background:

  1. Compile the project to an APK file if any files have changed since the last compilation.
  2. Create a new Run configuration for the Android project if one does not already exist. (We’ll look at Run configurations in a minute.)
  3. Install and run the application by starting or reusing an already running emulator instance with a fitting Android version or by deploying and running the application on a connected device (which must also run at least the minimum Android version you specified as the Minimum Required SDK Level when you created the project).

Note   The first time you run an Android application from within Eclipse, you will be asked whether you want ADT to react to messages in the output of the device/emulator. Since you always want all the information there is, simply click OK.

If you don’t have a device connected, the ADT plug-in will fire up one of the AVDs you saw listed in the AVD Manager window. The output should look like Figure 2-12.

9781430246770_Fig02-12.jpg

Figure 2-12.  The Hello World application in action

The emulator works almost exactly like a real device, and you can interact with it via your mouse just as you would with your finger on a device. Here are a few differences between a real device and the emulator:

  • The emulator supports only single-touch input. Simply use your mouse cursor and pretend it is your finger.
  • The emulator is missing some applications, such as the Google Play application.
  • To change the orientation of the device on the screen, don’t tilt your monitor. Instead, use the 7 key on your numeric keypad to change the orientation. You have to press the Num Lock key above the numeric keypad first to disable its number functionality.
  • The emulator is very slow. Do not assess the performance of your application by running it on the emulator.
  • Emulator versions prior to 4.0.3 only support OpenGL ES 1.x. OpenGL ES 2.0 is supported on emulator versions 4.0.3 and newer. We’ll talk about OpenGL ES in Chapter 7. The emulator will work fine for our basic tests. Once we get further into OpenGL, you’ll want to get a real device to test on, because even with the latest emulators that we’ve used, the OpenGL implementations (virtualized and software) are still a little buggy. For now, just keep in mind that you should not test any OpenGL ES applications on the emulator.

Play around with it a little and get comfortable.

Note   Starting a fresh emulator instance takes considerable time (up to 10 minutes depending on your hardware). You can leave the emulator running for your whole development session so you don’t have to restart it repeatedly, or you can check the Snapshot option when creating or editing the AVD, which will allow you to save and restore a snapshot of the virtual machine (VM), allowing for quick launch.

Sometimes when we run an Android application, the automatic emulator/device selection performed by the ADT plug-in is a hindrance. For example, we might have multiple devices/emulators connected, and we want to test our application on a specific device/emulator. To deal with this, we can turn off the automatic device/emulator selection in the Run configuration of the Android project. So, what is a Run configuration?

A Run configuration provides a way to tell Eclipse how it should start your application when you tell Eclipse to run the application. A Run configuration usually allows you to specify things such as command-line arguments passed to the application, VM arguments (in the case of Java SE desktop applications), and so on. Eclipse and third-party plug-ins offer different Run configurations for specific types of projects. The ADT plug-in adds an Android Application Run configuration to the set of available Run configurations. When we first ran our application earlier in the chapter, Eclipse and ADT created a new Android Application Run configuration for us in the background with default parameters.

To get to the Run configuration of your Android project, do the following:

  1. Right-click the project in the Package Explorer view and select Run As image Run Configurations.
  2. From the list on the left side, select the “hello world” project.
  3. On the right side of the dialog, you can now modify the name of the Run configuration, and change other settings on the Android, Target, and Commons tabs.
  4. To change automatic deployment to manual deployment, click the Target tab and select Manual.

When you run your application again, you’ll be prompted to select a compatible emulator or device on which to run the application. Figure 2-13 shows the dialog.

9781430246770_Fig02-13.jpg

Figure 2-13.  Choosing an emulator/device on which to run the application

The dialog shows all the running emulators and currently connected devices, as well as all other AVDs not currently running. You can choose any emulator or device on which to run your application. Note the red × beside the connected device. This usually indicates that the application won’t run on this device because its version is lower than the target SDK version we specified (14 versus 15 in this case). However, because we specified a minimum SDK version of 3 (Android 1.5), our application will actually work on this device as well.

Debugging and Profiling an Application

Sometimes your application will behave in unexpected ways or crash. To figure out what exactly is going wrong, you want to be able to debug your application.

Eclipse and ADT provide us with incredibly powerful debugging facilities for Android applications. We can set breakpoints in our source code, inspect variables and the current stack trace, and so forth.

Usually, you set breakpoints before debugging, to inspect the program state at certain points in the program. To set a breakpoint, simply open the source file in Eclipse and double-click the gray area in front of the line at which you want to set the breakpoint. For demonstration purposes, do that for line 23 in the HelloWorldActivity class. This will make the debugger stop each time you click the button. The Source Code view should show you a small circle in front of that line after you double-click it, as shown in Figure 2-14. You can remove breakpoints by double-clicking them again in the Source Code view.

9781430246770_Fig02-14.jpg

Figure 2-14.  Setting a breakpoint

Starting the debugging is much like running the application, as described in the previous section. Right-click the project in the Package Explorer view and select Debug As image Android Application. This creates a new Debug configuration for your project, just as in the case of simply running the application. You can change the default settings of that Debug configuration by choosing Debug As image Debug Configurations from the context menu.

Note   Instead of going through the context menu of the project in the Package Explorer view, you can use the Run menu to run and debug applications and to get access to the configurations.

If you start your first debugging session and a breakpoint is hit (for example, you tap the button in our application), Eclipse asks whether you want to switch to the Debug perspective, which you can confirm. Let’s have a look at that perspective first. Figure 2-15 shows how it would look after we start debugging our Hello World application.

9781430246770_Fig02-15.jpg

Figure 2-15.  The Debug perspective

If you remember our quick tour of Eclipse, then you’ll know there are several different perspectives, which consist of a set of views for a specific task. The Debug perspective looks quite different from the Java perspective.

  • The Debug view at the top left shows all currently running applications and the stack traces of all their threads if the applications are run in debug mode and are being suspended.
  • Below the Debug view is the Source Code view, which is also present in the Java perspective.
  • The Console view, also present in the Java perspective, prints out messages from the ADT plug-in, telling us what it is doing.
  • The Task List view (the tab with the label “Tasks” next to the Console view is the same as in the Java perspective. We usually have no need for it, you can savely close it.
  • The LogCat view will be one of your best friends on your journey. This view shows you logging output from the emulator/device on which your application is running. The logging output comes from system components, other applications, and your own application. The LogCat view will show you a stack trace when your application crashes and will also allow you to output your own logging messages at runtime. We’ll take a closer look at LogCat in the next section.
  • The Outline view, also present in the Java perspective, is not very useful in the Debug perspective. You will usually be concerned with breakpoints and variables, and the current line on which the program is suspended while debugging. We often remove the Outline view from the Debug perspective to leave more space for the other views.
  • The Variables view is especially useful for debugging purposes. When the debugger hits a breakpoint, you will be able to inspect and modify the variables in the current scope of the program.
  • The Breakpoints view shows a list of breakpoints you’ve set so far.

If you are curious, you’ve probably already clicked the button in the running application to see how the debugger reacts. It will stop at line 23, as we instructed it by setting a breakpoint there. You will also have noticed that the Variables view now shows the variables in the current scope, which consist of the activity itself (this) and the parameter of the method (v). You can drill down further into the variables by expanding them.

The Debug view shows you the stack trace of the current stack down to the method you are in currently. Note that you might have multiple threads running and can pause them at any time in the Debug view.

Finally, notice that the line where we set the breakpoint is highlighted, indicating the position in the code where the program is currently paused.

You can instruct the debugger to execute the current statement (by pressing F6), step into any methods that get called in the current method (by pressing F5), or continue the program execution normally (by pressing F8). Alternatively, you can use the items on the Run menu to achieve the same. In addition, notice that there are more stepping options than the ones we’ve just mentioned. As with everything, we suggest you experiment to see what works for you and what doesn’t.

Note   Curiosity is a building block for successfully developing Android games. You have to get intimate with your development environment to get the most out of it. A book of this scope can’t possibly explain all the nitty-gritty details of Eclipse, so we urge you to experiment.

LogCat and DDMS

The ADT Eclipse plug-in installs many new views and perspectives to be used in Eclipse. One of the most useful views is the LogCat view, which we touched on briefly in the previous section.

LogCat is the Android event-logging system that allows system components and applications to output logging information about various logging levels. Each log entry is composed of a timestamp, a logging level, the process ID from which the log came, a tag defined by the logging application itself, and the actual logging message.

The LogCat view gathers and displays this information from a connected emulator or device. Figure 2-16 shows some sample output from the LogCat view.

9781430246770_Fig02-16.jpg

Figure 2-16.  The LogCat view

Notice that there are a number of buttons at the top left and top right of the LogCat view:

  • The plus and minus buttons allow you to add and remove filters. There is already one filter that will only show log messages from our application.
  • The button to the right of the minus button allows you to edit an existing filter.
  • The drop-down list box allows you to select the log level that messages must have to be displayed in the window below.
  • The buttons to the right of the drop-down list box allow you to (in order from left to right) save the current log output, clear the log console, toggle the visibility of the left-side filter window, and halt updating the console window.

If several devices and emulators are currently connected, then the LogCat view will output the logging data of only one. To get finer-grained control and even more inspection options, you can switch to the DDMS perspective.

DDMS (Dalvik Debugging Monitor Server) provides a lot of in-depth information about the processes and Dalvik VMs running on all connected devices. You can switch to the DDMS perspective at any time via Window image Open Perspective image Other image DDMS. Figure 2-17 shows what the DDMS perspective usually looks like.

9781430246770_Fig02-17.jpg

Figure 2-17.  DDMS in action

As always, several specific views are suitable for our task at hand. In this case, we want to gather information about all the processes, their VMs and threads, the current state of the heap, LogCat information about a specific connected device, and so on.

  • The Devices view displays all currently connected emulators and devices, as well as all the processes running on them. Via the toolbar buttons of this view, you can perform various actions, including debugging a selected process, recording heap and thread information, and taking a screenshot.
  • The LogCat view is the same as in the Debug perspective, with the difference being that it will display the output of the device currently selected in the Devices view.
  • The Emulator Control view lets you alter the behavior of a running emulator instance. You can force the emulator to spoof GPS coordinates for testing, for example.
  • The Threads view, shown in Figure 2-17, displays information about the threads running on the process currently selected in the Devices view. The Threads view shows this information only if you also enable thread tracking, which can be achieved by clicking the fifth button from the left in the Devices view.
  • The Heap view gives information about the status of the heap on a device. As with the thread information, you have to enable heap tracking in the Devices view explicitly by clicking the second button from the left.
  • The Allocation Tracker view shows which classes have been allocated the most within the last few moments. This view provides a great way to hunt down memory leaks.
  • The Network Status view allows you to track the number of incoming and outgoing bytes sent over the network connetion of the connected Android device or emulator.
  • The File Explorer view allows you to modify files on the connected Android device or emulator instance. You can drag and drop files into this view as you would with your standard operating system file explorer.

DDMS is actually a stand-alone tool integrated with Eclipse via the ADT plug-in. You can also start DDMS as a stand-alone application from the $ANDROID_HOME/tools directory (%ANDROID_HOME%/tools on Windows). DDMS does not directly connect to devices, but uses the Android Debug Bridge (ADB), another tool included in the SDK. Let’s have a look at ADB to round off your knowledge about the Android development environment.

Using ADB

ADB lets you manage connected devices and emulator instances. It is actually a composite of three components:

  • A client that runs on the development machine, which you can start from the command line by issuing the command adb (which should work if you set up your environment variables as described earlier). When we talk about ADB, we refer to this command-line program.
  • A server that also runs on your development machine. The server is installed as a background service, and it is responsible for communication between an ADB program instance and any connected device or emulator instance.
  • The ADB daemon, which also runs as a background process on every emulator and device. The ADB server connects to this daemon for communication.

Usually, we use ADB via DDMS transparently and ignore its existence as a command-line tool. Sometimes ADB can come in handy for small tasks, so let’s quickly go over some of its functionality.

Note   Check out the ADB documentation on the Android Developers site at http://developer.android.com for a full reference list of the available commands.

A very useful task to perform with ADB is to query for all devices and emulators connected to the ADB server (and hence your development machine). To do this, execute the following command on the command line (note that > is not part of the command):

> adb devices

This will print a list of all connected devices and emulators with their respective serial numbers, and it will resemble the following output:

List of devices attached
HT97JL901589    device
HT019P803783    device

The serial number of a device or emulator is used to target specific subsequent commands at it. The following command will install an APK file called myapp.apk located on the development machine on the device with the serial number HT019P803783:

> adb –s HT019P803783 install myapp.apk

The –s argument can be used with any ADB command that performs an action that is targeted at a specific device.

Commands that copy files to and from the device or emulator also exist. The following command copies a local file called myfile.txt to the SD card of a device with the serial number HT019P803783:

> adb –s HT019P803783 push myfile.txt  /sdcard/myfile.txt

To pull a file called myfile.txt from the SD card, you could issue the following command:

> abd pull /sdcard/myfile.txt myfile.txt

If there’s only a single device or emulator currently connected to the ADB server, you can omit the serial number. The adb tool will automatically target the connected device or emulator for you.

It’s also possible to debug a device using ADB over the network (without USB). This is called ADB remote debugging and is possible on some devices. To check if your device can do it, find the Developer options and see if “ADB over network” is in the list of options. If so, you are in luck. Simply enable this remote debugging option on your device, and then run the following command:

> adb connect ipaddress

Once connected, the device will appear just as if it were connected via USB. If you don’t know the IP address, you can usually find it in the Wi-Fi settings by touching the current access point name.

Of course, the ADB tool offers many more possibilities. Most are exposed through DDMS, and we’ll usually use that instead of going to the command line. For quick tasks, though, the command-line tool is ideal.

Useful Third-Party Tools

The Android SDK and ADT may provide a whole lot of functionality, but there are a number of very useful third-party tools, some of which are listed next, that can help you later in your development. These tools do things like watch your CPU usage, tell you about your OpenGL rendering, help you to find bottlenecks in memory or file access, and more. You will need to match the chip in your device to the tool provided by the chip manufacturer. The following list includes the manufacturer and URL to help you with that matching. In no particular order:

We’re not going into the details of installing or using these tools, but when you’re ready to get serious about your game’s performance, make sure to circle back around to this section and dig in.

Summary

The Android development environment can be a bit intimidating at times. Luckily, you need only a subset of the available options to get started, and the “Using ADB” section toward the end of the chapter should have given you enough information to get started with some basic coding.

The big lesson to take away from this chapter is how the pieces fit together. The JDK and the Android SDK provide the basis for all Android development. They offer the tools to compile, deploy, and run applications on emulator instances and devices. To speed up development, we use Eclipse along with the ADT plug-in, which does all the hard work we’d otherwise have to do on the command line with the JDK and SDK tools. Eclipse itself is built on a few core concepts: workspaces, which manage projects; views, which provide specific functionality, such as source editing or LogCat output; perspectives, which tie together views for specific tasks such as debugging; and Run and Debug configurations, which allow you to specify the startup settings used when you run or debug applications.

The secret to mastering all this is practice, as dull as that may sound. Throughout the book, we’ll implement several projects that should make you more comfortable with the Android development environment. At the end of the day, though, it is up to you to take it all one step further.

With all this information, you can move on to the reason you’re reading this book in the first place: developing games.

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

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