© Mario Zechner, J.F. DiMarzio and Robert Green 2016

Mario Zechner, J. F. DiMarzio and Robert Green, Beginning Android Games, 10.1007/978-1-4842-0472-6_2

2. First Steps with Android Studio

Mario Zechner, J. F. DiMarzio2 and Robert Green3

(1)Graz, Steiermark, Austria

(2)Celebration, Florida, USA

(3)Portland, Oregon, USA

The Android Studio and the Android SDK provide a set of tools that enable 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 Android Studio 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 by 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 8

  2. Android Studio

  3. The Android Software Development Kit (Android SDK)

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.

Setting Up the JDK

Download the JDK version specific to 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 that points 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.

Installing Android Studio

At the time this book was written, Android Studio was on version 2.2. Simply find the download for the latest version on the Android developer site and extract it to a folder of your choice. Once installed, you can create a shortcut on your desktop to the Android Studio executable in the root directory of your Android Studio installation .

Setting Up the Android SDK

The Android SDK is 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 that points to the root directory of the SDK installation, then 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, which is responsible for creating virtual devices used by the emulator. These tools alone are not sufficient to start developing, so you’ll 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. Or, you can launch the SDK Manager from within Android Studio by clicking on Tools >> Android >> SDK Manager. Then, you can click on Launch Standalone SDK Manager.

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.

A340874_3_En_2_Fig1_HTML.jpg
Figure 2-1. First contact with the SDK Manager

You can use the SDK Manager at any time 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.

A Quick Tour of Android Studio

IntelliJ, or IntelliJ IDEA, is a Java IDE developed by JetBrains. It has become the de facto IDE for Java development because of its strong feature set. Android Studio is based on the open source community edition of IntelliJ IDEA. This means that many of the features that make IntelliJ IDEA an extraordinary IDE for Java development also make Android Studio an extraordinary IDE for Java development for Android.

IntelliJ has many features in general, and it also has a complete set of tools just for assisting with code generation that have been carried over to Android Studio. The following sections highlight just a few of these features.

Code Completion

Code Completion is one feature of IntelliJ that is used most often in Android development. Let’s say we create a function as seen here:

String mystring;

public void setMyProperty(String mystring) {
        this.mystring = mystring;
    }


private void DoSomething(String someValue){
    setMyProperty();
}

This very simplistic function takes in a String variable someValue. Notice that the function calls setMyProperty(). We can assume that setMyProperty(), is a setter that takes in a String value (as shown in the previous code sample). Place your cursor inside the parentheses of setMyProperty() and press Ctrl+Alt+Space. This will bring up the Android Studio autocomplete window, as seen in Figure 2-2.

A340874_3_En_2_Fig2_HTML.jpg
Figure 2-2. The IntelliJ autocomplete window

The main thing to notice about this window is that it not only lists for you the available String values that you could pass into setMyProperty(), but also sorts them by the ones that it feels you are most likely to use. In this case, someValue—the value being passed into our functionis displayed first.

Breakpoints

Later in this book, I will walk through debugging your game. However, let’s take a quick moment to cover breakpoints. Breakpoints are like bookmarks in your code that tell Android Studio where you want to pause execution while you are debugging.

To place a breakpoint , click in the right-hand margin of your code editor next to the line where you want code execution to pause. A set breakpoint is illustrated in Figure 2-3.

A340874_3_En_2_Fig3_HTML.jpg
Figure 2-3. A set breakpoint

One of the great things about breakpoints in Android Studio is that you can set them with conditions. If you right-click on your breakpoint, you will get a context menu that can be expanded, as seen in Figure 2-4.

A340874_3_En_2_Fig4_HTML.jpg
Figure 2-4. The breakpoint context menu

From this window you can set conditions on your breakpoints. For example, if you have an integer value named myInteger that you set a breakpoint on, you can set a condition to only break if the value of myInteger is greater than 100.

Any condition that can be evaluated as true or false can be used as a breakpoint condition.

Creating a New Project in Android Studio and Writing Your Code

With our development set up, we can now create our first Android project in Android Studio. The built-in wizard makes creating new Android projects very easy.

Creating the Project

There are two ways to create a new Android project. The first is to click on File >> New >> New Project from the menu bar. This is the standard way to create a new project in Android Studio. From here, the Create New Project wizard opens.

If this is the first time you have opened Android Studio, or if you have recently closed an active project, just click on “Start a new Android Studio project” in the Welcome to Android Studio window, which also opens the wizard.

Once you are in the Create New 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 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 “helloworld.com” in this example. Click Next to continue.

  3. Select Phone and Table as the form factors that you wish to run on.

  4. Specify the minimum required SDK. This is the lowest Android version your application will support. We’ll choose Android 7.0 (Nougat, API level 24). (The API level may be 25 by the time Nougat is fully released.)

    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 6.X 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 4.3), then your application will crash if the user accesses API features that are available only in version 7. In this case, you’d need to detect the supported SDK version during runtime and only access the 7 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.

  5. Click Next. You’ll be shown a dialog that lets you select a default activity for your application. We’ll select Empty Activity and click Next.

  6. 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 layout name to “activity_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 your Hello World project. If you expand it and all its children, you’ll see something like Figure 2-5. (If you do not see the same layout as in Figure 2-5, switch to the Project view from the dropdown box located above the layout.) 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 Create New Project wizard.

  • build/generated/ contains Java source files generated by the Android build system. You shouldn’t modify them, as they get regenerated automatically.

  • libs/ holds any additional JAR files that we want our application to depend on.

  • 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 make up 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).

A340874_3_En_2_Fig5_HTML.jpg
Figure 2-5. Hello World project structure

We can easily add new source files, folders, and other resources in the Project 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.

Writing the Application Code

We still haven’t written a single line of code, so let’s change that. The Create New 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 Project view. We’ll replace that template code with the code in Listing 2-1.

Listing 2-1. HelloWorldActivity.java
package com.helloworld.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class HelloWorldActivity extends AppCompatActivity
                                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.helloworld;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

Next, we define our HelloWorldActivity and let it extend the base class AppCompatActivity, 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 and the “soft buttons” at the bottom of the screendepending on the device). Additionally, we let HelloWorldActivity 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 AppCompatActivity
                                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 can implement the 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.

@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. Android Studio 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 to just be amazed at its glory. There are two ways in which 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’s 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 in order 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 so by clicking Tools >> Android >> AVD Manager. Let’s walk through the steps of creating a custom AVD:

  1. Click the Create Virtual Device… button on the lower-left side of the AVD Manager screen, which opens the Virtual Device Configuration dialog, shown in Figure 2-6.

    A340874_3_En_2_Fig6_HTML.jpg
    Figure 2-6. Virtual Device Configuration dialog
  2. Select the correct hardware profile. In this example, we’ll select a Phone >> Nexus 5. Click Next to continue.

  3. The system image specifies the Android version that the AVD should use. For our simple “Hello World” project, you can select x86Images >> Jelly Bean. Note: You may have to download it before you can select it. Don’t worry though, the AVD Manager has made this a painless process; just click on the “Download” link and AVD Manager will take care of the rest.

  4. Click Finish to create your emulator.

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. 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. Open the Standalone SDK Manager. Find the Intel x86 Emulator Accelerator (HAXM installer), select it, and install (see Figure 2-7).

    A340874_3_En_2_Fig7_HTML.jpg
    Figure 2-7. Selecting HAXM installer
  2. Now, edit your emulator’s image by opening the AVD Manager and clicking on the green pencil icon next to the emulator name. Set the graphics to Hardware GLES20, as shown in Figure 2-8. Note that if you are running on an older computer and your GPU is not up to the task of emulating the Android screen, you may want to select Software GLES20.

    A340874_3_En_2_Fig8_HTML.jpg
    Figure 2-8. Creating the x86 AVD with GPU emulation enabled

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 Android Studio by clicking the Run button on the toolbar. Android Studio will then perform the following steps in the background:

  1. Compile the project, using Gradle, to an APK file if any files have changed since the last compilation.

  2. Install and run the application by starting or reusing an already running emulator instance with an appropriate 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).

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-9.

A340874_3_En_2_Fig9_HTML.jpg
Figure 2-9. 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 by default. Simply use your mouse cursor and pretend it is your finger. To emulate multi-touch, hold the CTRL button on Windows at the same time as you click with the mouse (or the Command button on a Mac).

  • 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, click the Rotate Left or Rotate Right buttons.

  • The emulator can be slow. Do not assess the speed 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 be cautious when testing OpenGL ES applications on the emulator.

Play around with it a little and get comfortable.

Note

Starting a fresh emulator instance can take a considerable amount of time (up to ten 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.

Debugging and Profiling an Application

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

Android Studio provides 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 so as to inspect the program state at certain points in the program. To set a breakpoint, simply open the source file in Android Studio and 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 Editor tab should show you a small circle in front of that line after you click it, as shown in Figure 2-10. You can remove breakpoints by clicking them again in the Editor tab

A340874_3_En_2_Fig10_HTML.jpg
Figure 2-10. Setting a breakpoint

Starting the debugging is much like running the application, as described in the previous section. However, rather than clicking on the Run button, click on the Debug button.

Let’s take a look at what information is available to you when you are debugging an application.

  • The Debugger at the bottom left shows all currently running applications and the stack traces of all their threads if the applications are being run in debug mode and are being suspended.

  • The Console window prints out messages from the ADT plug-in that tell us what it is doing.

  • The logcat view in the Android Monitor 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 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.

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 to 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 F8), step into any methods that get called in the current method (by pressing F7), or continue the program execution normally (by pressing F9). Alternatively, you can use the items on the Run menu to achieve the same things. 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 Android Studio, so we urge you to experiment.

LogCat

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-11 shows some sample output from the logcat view.

A340874_3_En_2_Fig11_HTML.jpg
Figure 2-11. The logcat view

If several devices and emulators are currently connected, then the logcat view will output the logging data of only one.

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 this 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 Android Studio, which does all the hard work we’d otherwise have to do on the command line with the JDK and SDK tools. Android Studio provides specific functionality, such as source editing or logcat output and debugging.

The secret to mastering all of 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
3.135.207.129