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:
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:
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.
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.
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:
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.
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.
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.
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:
Figure 2-3. Adding a repository
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.
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.
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:
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:
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.
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 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 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.
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:
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.
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 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:
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.
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.
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.
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:
With these changes, your application can run on all the Android versions that are currently out in the wild!
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:
In both cases, we have to do a little bit of setup work before we can finally see our application in action.
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:
Figure 2-7. Edit Android Virtual Device (AVD) dialog
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:
Figure 2-8. Selecting the x86 Atom System Image for ICS
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!
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.
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 Android Application (or you can click the Run button on the toolbar). Eclipse will then perform the following steps in the background:
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.
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:
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:
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.
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.
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 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 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.
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.
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.
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.
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:
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 Open Perspective Other DDMS. Figure 2-17 shows what the DDMS perspective usually looks like.
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.
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.
ADB lets you manage connected devices and emulator instances. It is actually a composite of three components:
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.
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.