Android Studio for beginners, Part 1: Installation and setup

Install Android Studio and start your first Android project.

For some years now it’s been clear that Android is a force to be reckoned with in the mobile OS landscape. This Java-based technology has sparked a new gold rush, with programmers competing to make money from their mobile apps. Android jobs are also plentiful, as shown by a quick job search using Indeed.com.

If you’re new to Android Studio, this tutorial series will get you started. I’ll briefly introduce the Android development platform, then show you how to download, install, and run the software. After that, we’ll spend most of our time actually using Android Studio to develop an animated mobile app:

  • In Part 1, you’ll start up your first Android project and get to know Android Studio’s main window.
  • In Part 2, you’ll code the app, learning how to use Android Studio to enter source code and resources into the project.
  • In Part 3, we’ll build and run the app, using both an emulated hardware device and a Kindle Fire tablet.
  • In Part 4, I’ll show you how to use use built-in tools and plugins to debug Android and improve your coding productivity.

Examples in this series are from the most stable version of Android at the time of this writing, Android 3.2.1.


Get started with Android Studio

Android Studio is Google’s officially supported IDE for developing Android apps. This IDE is based on IntelliJ IDEA, which offers a powerful code editor and developer tools. Android Studio 3.2.1 includes the following features:

  • A flexible Gradle-based build system
  • A fast and feature-rich emulator
  • A unified environment where you can develop for all Android devices
  • Instant Run to push changes to your running app without building a new APK
  • Code templates and GitHub integration to help you build common app features and import sample code
  • Extensive testing tools and frameworks
  • Lint tools to help you catch performance, usability, version compatibility, and other problems
  • C++ and NDK support
  • Built-in support for Google Cloud Platform, making it easy to integrate Google Cloud Messaging and Google App Engine
  • Plugin architecture for extending Android Studio via plugins

Download Android Studio

Google provides Android Studio for the Windows, Mac OS X, and Linux platforms. You can download Android Studio from the Android Studio homepage, where you’ll also find the traditional SDKs with Android Studio’s command-line tools.


Windows requirements

  • Microsoft Windows 7/8/10 (32-bit or 64-bit)
  • 3 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator)
  • 2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for Android SDK and emulator system image)
  • 1280 x 800 minimum screen resolution

Mac OS requirements

  • Mac OS X 10.10 (Yosemite) or higher, up to 10.13 (High Sierra)
  • 3 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator)
  • 2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for Android SDK and emulator system image)
  • 1280 x 800 minimum screen resolution

Linux OS requirements

  • GNOME or KDE desktop. Tested on Ubuntu 14.04 LTS, Trusty Tahr (64-bit distribution capable of running 32-bit applications)
  • 64-bit distribution capable of running 32-bit applications
  • GNU C Library (glibc) 2.19 or later
  • 3 GB RAM minimum, 8 GB RAM recommended (plus 1 GB for the Android Emulator)
  • 2 GB of available disk space minimum, 4 GB recommended (500 MB for IDE plus 1.5 GB for Android SDK and emulator system image)
  • 1280 x 800 minimum screen resolution

Once you’ve ensured that your operating system is compatible with Android Studio 3.2.1 or higher, download the appropriate Android Studio distribution file. The Android Studio download page auto-detected that I’m running a 64-bit Windows operating system and selected android-studio-ide-181.5056338-windows.exe (927 MB) for me to download.

Android SDK command-line tools

android-studio-ide-181.5056338-windows.exe includes an installer and the Android SDK command-line tools. If you don’t need or want to use Android Studio, you can download only the Android SDK command-line tools.

Installing Android Studio on 64-bit Windows 10

I launched android-studio-ide-181.5056338-windows.exe to start the installation process. The installer responded by presenting the Android Studio Setup dialog box shown in Figure 1.

Figure 1. Set up Android Studio

Clicking Next took me to the following panel, which provides the option to decline installing an Android Virtual Device (AVD).

Figure 2. Install an Android AVD?

I chose to keep the default settings. After clicking Next, I was taken to the Configuration Settings panel, where I was asked to choose where to install Android Studio.

Figure 3. The installation location must have at least 500 MB free space

I kept the default installation location and clicked Next, and was greeted with the Choose Start Menu Folder panel.

Figure 4. Select the folder in which to store Android Studio shortcuts

I kept the default setting and clicked Install. The following Installing panel appeared:

Figure 5. This panel shows the progress of the installation

Clicking Show details causes the names of files being installed and other activities to be displayed. When installation finished, the Installation Complete panel appeared.

Figure 6. The Next button is enabled when installation completes

After clicking Next, the installer presented the Completing Android Studio Setup panel.

Figure 7. Leave the Start Android Studio checkbox checked to run this software

To complete the installation, I left the Start Android Studio box checked and clicked Finish.


Running Android Studio

The first time Android Studio runs, it presents a Complete Installation dialog box that offers the option of importing settings from a previous installation.

Figure 8. A previous installation’s settings can be imported

I chose not to import settings (the default selection) and clicked OK, and was rewarded with the following splash screen:

Figure 9. Android Studio’s splash screen

I also observed the following Finding Available SDK Components message box.

Figure 10. Android Studio downloads any SDK components that are needed (and available)

At this point, Android Studio presented the following Android Studio Setup Wizard dialog box:

Figure 11. The wizard provides setup and app-porting capabilities (click to enlarge

I clicked Next, and the wizard invited me to select an installation type. I kept the default standard setting.

Figure 12. Choose an installation type (click to enlarge)

I was then given the opportunity to choose a user interface theme.

Figure 13. Put the bite on Android Studio by choosing the Darcula theme (click to enlarge)

I kept the default IntelliJ setting and clicked Next. Android Studio next provided the opportunity to verify settings.

Figure 14. Android Studio identifies additional SDK components that will be downloaded (click to enlarge)

I clicked Finish and Android Studio began the process of downloading SDK components.

Figure 15. The wizard downloads and unzips SDK components (click to enlarge)

It can take several minutes for this part of the setup to finish. Clicking Show Details might relieve some boredom by revealing the various files being downloaded and unzipped.

Figure 16. The wizard identifies the various archives being downloaded (click to enlarge)

For my AMD-based computer, an unpleasant surprise awaited after the components had completely downloaded and unzipped:

Figure 17. Intel-based hardware acceleration is unavailable (click to enlarge)

My options are to either put up with the slow emulator or use an Android device to speed up development. In Part 3 I’ll show you how I resolved this issue.

Finally, I clicked Finish to complete the wizard. The Welcome to Android Studio dialog box appeared.

Figure 18. Welcome to Android Studio (click to enlarge)

This dialog box is used to start up a new Android Studio project, work with an existing project, and more. It can be accessed by selecting Android Studio from the Windows Start menu, or the equivalent on another platform.


Your first Android Studio mobile app

The quickest way to get to know Android Studio is to use it to develop an app. We’ll start with a variation on the “Hello, World” application: a little mobile app that displays a “Welcome to Android” message.

In the steps that follow, you’ll start a new Android Studio project and get to know the main window, including the editor window that you’ll use to code the app in Part 2.


Starting a new project

From our setup so far, you should still have Android Studio running with the Welcome to Android Studio dialog box. From here, click Start a new Android Studio project. Android Studio will respond with the Create New Project dialog box shown in Figure 19.

Figure 19. Create a new Android project (click to enlarge)

Enter W2A (Welcome to Android) as the application name and javajeff.ca as the company domain name. On my desktop, I observed C:\Users\JEFF\AndroidStudioProjects\W2A as the project location. Click Next to select your target devices.

Figure 20. Select your target device categories (click to enlarge)

Android Studio lets you select form factors, or categories of target devices, for every app you create. I kept the default setting.

Click Next, and you will be given the opportunity to choose a template for your app’s main activity. For now we’ll stick with Empty Activity. Select this template (if necessary) and click Next.

Figure 21. Specify an activity template (click to enlarge)

Next you’ll customize the activity:

Figure 22. Customize your activity (click to enlarge)

Enter W2A as the activity name and main as the layout name, and click Next to complete this step.


Reconfigured buttons

The next time you create an app for the chosen target device category, you’ll probably discover that Next is disabled and Finish is enabled.

The first time you use Android Studio, you’ll discover that it has to download some files related to its constraint layout, which is used to build responsive user interfaces:

Figure 23. Constraint layout is the default layout used by Android Studio for new app projects (click to enlarge)

Android Studio enables Finish after downloading the constraint layout files. Click this button and Android Studio takes you to the main window.

Figure 24. Android Studio’s main window reveals that it has built a skeletal W2A app (click to enlarge)

The main window is divided into a menu bar and several other areas, which are identified in Figures 25 and 26. (Note that Figures 25 and 26 are courtesy of Google.)

Figure 25. The different areas that comprise the main window

Figure 26. The main window presenting a toolbar, editor window(s), and other features

Check out the Meet Android Studio page to learn more about Android Studio’s user interface.


Accessing AVD Manager and SDK Manager

To access the traditional AVD Manager or SDK Manager, select AVD Manager or SDK Manager from Android Studio’s Tools menu.

The Project and editor windows

When you enter the main window (see Figure 24), you observe the Project window showing only app and Gradle Scripts. You’ll have to expand the app branch of the project tree to observe more details.

Figure 27. The Project window and an editor window show the skeletal W2A activity source code (click to enlarge)

The Project window is organized into a tree whose main branches are app and Gradle Scripts. The app branch is further organized into manifests, java, generatedJava, and res subbranches:


Android Studio for beginners, Part 2: Explore and code the app

Write your first animated Android app with Android Studio’s Project editor

In Part 1 of this beginner’s introduction to Android Studio, you set up Android Studio in your development environment and got to know the user interface. Now, in Part 2, you’ll code your first app.

The animated mobile app consists of a single activity, which presents Google’s Android robot character and a button for animating the character. Clicking the button causes the character to gradually change color from green to red to blue, then back to green. While the app isn’t especially useful, writing it will help you get comfortable with using Android Studio.

Note that this series has been updated for Android Studio 3.2.1, the current stable release as of this writing.


Android Studio’s Project and editor windows

I introduced Android Studio’s main window at the end of Part 1. This window is divided into several areas, including a Project window where you identify an app’s resource files, and various editor windows where you’ll write the code and specify resources for mobile apps in Android Studio. The Project window and an editor window are shown in Figure 1.

Figure 1. Android Studio’s Project window and an editor window (click to enlarge)

The Project window highlights W2A, which is the name of the app’s W2A.java source file (although the .java file extension isn’t shown). Corresponding to W2A is an editor window, reached by double-clicking W2A in the Project window. The editor window reveals the file’s current contents, in this case the skeletal Java source code for the app’s main activity.

Each editor window is associated with a tab. For example, W2A’s editor window is associated with a W2A.java tab. A second tab identified as main.xml (the default XML-based layout for the app’s main activity) is also shown. You move from one editor window to another by clicking the window’s tab.


The Android example app

The example app (W2A.java) consists of a main activity that displays the Android robot character and a button. When the user presses the button, the robot animates through a series of colors. In this section, we’ll explore the activity’s source code and resources.


Explore and code the Android example app

The activity’s source code is stored in the file W2A.java, presented in Listing 1.


Listing 1. W2A.java

package ca.javajeff.w2a;

import android.app.Activity;

import android.graphics.drawable.AnimationDrawable;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;
import android.widget.ImageView;

public class W2A extends Activity
{
AnimationDrawable androidAnimation;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView androidImage = (ImageView) findViewById(R.id.android);
androidImage.setBackgroundResource(R.drawable.android_animate);
androidAnimation = (AnimationDrawable) androidImage.getBackground();
final Button btnAnimate = (Button) findViewById(R.id.animate);
View.OnClickListener ocl;
ocl = new View.OnClickListener()
{
@Override
public void onClick(View v)
{
androidAnimation.stop();
androidAnimation.start();
}
};
btnAnimate.setOnClickListener(ocl);
}
}

The W2A.java file starts with a package statement, which names the package (ca.javajeff.w2a) that stores the W2A class. This is followed by a series of import statements for various Android API types. Next, the code describes the W2A class, which extends android.app.Activity.

W2A first declares an androidAnimation instance field of type android.graphics.drawable.AnimationDrawable. Objects of type AnimationDrawable describe frame-by-frame animations, in which the current drawable is replaced with the next drawable in the animation sequence.


What is a drawable?

A drawable is something that can be drawn, such as an image. AnimationDrawable indirectly extends the abstract android.graphics.drawable.Drawable class, which is a general abstraction for a drawable.

The onCreate() method

All of the app’s work takes place in W2A's overriding onCreate(Bundle) method: no other methods are required, which helps to keep this app simple.

onCreate(Bundle) first invokes its same-named superclass method, a rule that must be followed by all overriding activity methods.

This method then executes setContentView(R.layout.main) to establish the app’s user interface. R.layout.main is an identifier (ID) for an application resource, which resides in a separate file. You interpret this ID as follows:

  • R is the name of a class that’s generated when the app is being built. This class is named R because its content identifies various kinds of application resources, including layouts, images, strings, and colors.
  • layout is the name of a class that’s nested within R. An application resource whose ID is stored in this class describes a specific layout resource. Each kind of application resource is associated with a nested class that’s named in a similar fashion. For example, string identifies string resources.
  • main is the name of an int-based constant declared within layout. This resource ID identifies the main layout resource. Specifically, main refers to a main.xml file that stores the main activity’s layout information. main is W2A's only layout resource.

Passing R.layout.main to Activity's void setContentView(int layoutResID) method instructs Android to create a user interface screen using the layout information stored in main.xml. Behind the scenes, Android creates the user interface components described in main.xml and positions them on the device screen as specified by main.xml's layout data.

The screen is based on views (abstractions of user interface components) and view groups (views that group related user interface components). Views are instances of classes that subclass the android.view.View class and are analogous to AWT/Swing components. View groups are instances of classes that subclass the abstract android.view.ViewGroup class and are analogous to AWT/Swing containers. Android refers to specific views (such as buttons or spinners) as widgets.

Continuing, onCreate(Bundle) executes ImageView androidImage = (ImageView) findViewById(R.id.android);. This statement first calls View's View findViewById(int id) method to find the android.widget.ImageView element declared in main.xml and identified as android. It instantiates ImageView and initializes it to the values declared in the main.xml file. The statement then saves this object’s reference in local variable androidImage.


ImageView and AnimationDrawable

Next, the androidImage.setBackgroundResource(R.drawable.android_animate); statement invokes ImageView's inherited (from View) void setBackgroundResource(int resID) method, setting the view’s background to the resource identified by resID. The R.drawable.android_animate argument identifies an XML file named android_animate.xml (presented later), which stores information on the animation, and which is stored in res's drawable subdirectory. The setBackgroundResource() call links the androidImage view to the sequence of images described by android_animate.xml, which will be drawn on this view. The initial image is drawn as a result of this method call.

ImageView lets an app animate a sequence of drawables by calling AnimationDrawable methods. Before the app can do this, it must obtain ImageView's AnimationDrawable. The androidAnimation = (AnimationDrawable) androidImage.getBackground(); assignment statement that follows accomplishes this task by invoking ImageView's inherited (from View) Drawable getBackground() method. This method returns the AnimationDrawable for the given ImageView, which is subsequently assigned to the androidAnimation field. The AnimationDrawable instance is used to start and stop an animation, a process I’ll describe shortly.

Finally, onCreate(Bundle) creates the Animate button. It invokes findByViewId(int) to obtain the button information from main.xml, then instantiates the android.widget.Button class.

It then employs the View class’s nested onClickListener interface to create a listener object. This object’s void onClick(View v) method is invoked whenever the user clicks the button. The listener is registered with its Button object by calling View's void setOnClickListener(AdapterView.OnClickListener listener) method.

To stop, then start the animation, Animate’s click listener invokes androidAnimation.stop(); followed by androidAnimation.start();. The stop() method is called before start() to ensure that a subsequent click of the Animate button causes a new animation to begin.


Update and save your code

Before we continue, replace the skeletal code in your W2A.java tab with the code from Listing 1. Save the contents of this window by pressing Ctrl+S, or select Save All from the File menu.


Coding the Android app’s main.xml

The app’s main activity is associated with an XML-based layout, which is stored in file main.xml, and which is presented in Listing 2.


Listing 2. main.xml

<?xml version=“1.0” encoding=“utf-8”?>
<LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android
android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:gravity=“center”
android:background=“#ffffff”>
<ImageView android:id=“@+id/android”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginBottom=“10dip”/>
<Button android:id=“@+id/animate”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“@string/animate”/>
</LinearLayout>

After the XML declaration, Listing 2 declares a LinearLayout element that specifies a layout (a view group that arranges contained views on an Android device’s screen in some manner) for arranging contained widgets (including nested layouts) either horizontally or vertically across the screen.

The <LinearLayout> tag specifies several attributes for controlling this linear layout. These attributes include the following:

  • orientation identifies the linear layout as horizontal or vertical. Contained widgets are laid out horizontally or vertically, and the default orientation is horizontal. “horizontal” and “vertical” are the only legal values that can be assigned to this attribute.
  • layout_width identifies the width of the layout. Legal values include “fill_parent” (to be as wide as the parent) and “wrap_content” (to be wide enough to enclose content). (Note that fill_parent was renamed to match_parent in Android 2.2, but is still supported and widely used.)
  • layout_height identifies the height of the layout. Legal values include “fill_parent” (to be as tall as the parent) and “wrap_content” (to be tall enough to enclose content).
  • gravity identifies how the layout is positioned relative to the screen. For example, “center” specifies that the layout should be centered horizontally and vertically on the screen.
  • background identifies a background image, a gradient, or a solid color. For simplicity, I’ve hardcoded a hexadecimal color identifier to signify a solid white background (#ffffff). (Colors would normally be stored in colors.xml and referenced from this file.)

The LinearLayout element encapsulates ImageView and Button elements. Each of these elements specifies an id attribute, which identifies the element so that it can be referenced from code. The resource identifier (special syntax that begins with @) assigned to this attribute begins with the @+id prefix. For example, @+id/android identifies the ImageView element as android; this element is referenced from code by specifying R.id.android.

These elements also specify layout_width and layout_height attributes for determining how their content is laid out. Each attribute is assigned wrap_content so that the element will appear at its natural size.

ImageView specifies a layout_marginBottom attribute to identify a space separator between itself and the button that follows vertically. The space is specified as 10 dips, or density-independent pixels. These are virtual pixels that apps can use to express layout dimensions/positions in a screen density-independent way.


Density-independent pixels

A density-independent pixel (dip) is equivalent to one physical pixel on a 160-dpi screen, the baseline density assumed by Android. At runtime, Android transparently handles any scaling of the required dip units, based on the actual density of the screen in use. Dip units are converted to screen pixels via the equation: pixels = dips * (density / 160). For example, on a 240-dpi screen, 1 dip equals 1.5 physical pixels. Google recommends using dip units to define your app’s user interface to ensure proper display of the user interface on different device screens.

Choosing and saving a new layout

Android Studio for beginners, Part 3: Build and run the app

Build your app with Gradle, then run it with the Android device emulator or Kindle Fire tablet

In Android Studio for beginners, Part 2, you created your first animated mobile app using Android Studio. Now, Part 3 will take you through the steps to build and run the app in an Android device emulator or live device.

We’ll first use Gradle to build the app’s application package (APK) file. Then I’ll show you how to set up and run the app on an Android device emulator or an actual device, in this case a Kindle Fire tablet. I’ll also show you how I resolved a couple of issues with Android Studio’s device emulator setup, including the infamous Timed out while waiting error.

Note that this series has been updated for Android Studio 3.2.1, the current stable release as of this writing.


Building your Android app

If you followed along in Part 2, you’ve already loaded your source code and resource files into your Android Studio project. Now you’re ready to build the app for the first time.

If you haven’t already, start up Android Studio. The menu bar provides a Build menu, which you’ll use to access Gradle and build the example application.

Select Make Project from the Build menu. You should observe a Gradle Build Running message on the status bar. After a little while, you should observe a Gradle Build Finished message. Click on this message and the Event Log window appears.

Figure 1. The event log reveals no problems (click to enlarge)

There’s more than one way to build an Android app. For example, you could select Rebuild Project from the Build menu. Another approach is to actually run the app. If necessary, Gradle will automatically rebuild the app before its APK is installed and the app is run.


Do more with the Build menu

Android Studio’s Build menu lets you perform several build tasks. For example, you could use the Generate Signed Bundle / APK menu item to build a signed app bundle or APK.


Running your Android app

In this section I’ll show you how to run an Android application two ways: first on an emulated device, and then on an actual device. For my example I’ll be using an Amazon Kindle Fire HD tablet, but the instructions should generally apply to the device of your choice.


Run your Android app on an emulated device

You can run the example application (W2A) or any other app by selecting Run ‘app’ in the Run menu. Alternatively, you can click the green triangle button on the toolbar. Either way, Android Studio responds with the Select Deployment Target dialog box.

Figure 2. Android Debug Bridge (ADB) must be initialized in order to run an Android app (click to enlarge)

After you’ve initialized the Android Debug Bridge, the message in Figure 2 will be replaced by a list of all connected USB devices and running emulators that have been detected by Android Studio.

Figure 3. Select the device or emulator to run the app (click to enlarge)

In this case, Android Studio hasn’t detected any connected USB devices or emulators, so you’ll need to configure a new virtual device. Clicking Create New Virtual Device launches the dialog box shown in Figure 4.

Figure 4. Use the Virtual Device Configuration dialog box to choose a device to emulate (click to enlarge)

Select whatever device you want to emulate. For this example, I selected the highlighted (default) Nexus 5X. Click Next after you’ve made your selection.

The resulting System Image panel invites you to select a system image for this device emulation. I clicked the Other Images tab followed by IceCreamSandwich – the highlighted line in Figure 5.

Figure 5. Select a system image for device emulation (click to enlarge)

You’ll need to click the Download link to download whatever system image you’ve chosen. The image isn’t installed by default. Before you can install the system image, you will also be presented with a license agreement.

Figure 6. Accept the license agreement and click Next (click to enlarge)

You must accept the license agreement to continue. After accepting the license agreement, you will be presented with the Component Installer panel. At this point, the system image components are being downloaded and installed.

Figure 7. Click Finish when installation is complete (click to enlarge)

Before continuing, it’s a good idea to check your work. Use the Back button to navigate out of the installation dialogs and back to the Android Virtual Device (AVD) panel. Here you can verify your settings for the emulator AVD that will run your emulated device.

Figure 8. Keep the default settings and click Finish (click to enlarge)

For this example, I chose to keep the default settings. You can keep the defaults or make whatever changes are necessary, then click Finish. You should now be returned to the Select Deployment Target dialog box.

Figure 9. Nexus 5X API 15 is available in the Android Virtual Device list (click to enlarge)

Highlight your chosen device entry and click OK.


Android version history

Take a virtual tour of Android versions, from Cupcake 1.0 to Pie, released in August 2018.

Troubleshooting the Android device emulator

Unfortunately, at this point in the installation you may receive a message that Instant Run is not supported. In my case, the status bar presented a Waiting for target device to come online message and an empty emulator window appeared.

Figure 10. The blank screen of death (click to enlarge)

Shortly after the emulator window appeared, the Windows-based qemu-system-armel.exe program that’s responsible for creating this window crashed. (Recall from Part 1 that I’m running a 64-bit Windows operating system.)

Figure 11. Windows notification about the crashed executable

At first, I wasn’t sure how to fix this problem. Fortunately, the next time I ran Android Studio 3.2.1, I observed an IDE and Plugin Updates message in the lower-right area of Android Studio’s main window.

Figure 12. Click the Update link and follow directions to update the Android emulator (click to enlarge)

I clicked the update link and followed directions to update the emulator, which resulted in a new qemu-system-armel.exe file.

No more crashes, but I quickly hit another snag.


Waiting for target device to come online

When I tried running the app in my emulator, the status bar once again displayed a Waiting for target device to come online message, followed by the empty emulator window.

Eventually, Android Studio gave up on waiting and presented the error message: Error while waiting for device: Timed out after 300 seconds waiting for emulator to come online.

When I googled these messages, I discovered that many others have experienced this issue. Some developers have solved this problem by enabling the AVD’s Graphics Processing Unit hardware. It took some exploring to figure this out, so I’ll share what I learned, and hopefully save you some time.


Enable AVD’s Graphics Processing Unit

An AVD consists of several files and directories located in a directory with the .avd extension. For example, the AVD I created is located in C:\USERS\Jeff.android\avd\Nexus_5X_API_15.avd.

This directory contains a config.ini file, which stores configuration settings for the AVD. Two settings caught my attention:

hw.gpu.enabled=no
hw.gpu.mode=off

I changed these entries to the following:

hw.gpu.enabled=yes
hw.gpu.mode=on

Enabling the Graphics Processing Unit solved the problem: the next time I attempted to run the app, I observed a properly running emulated Nexus 5X device.

Figure 13. Unlock the device to see the app (click to enlarge)

I unlocked the device by using the mouse to swipe the lock icon to the right. At this point the emulator showed the example app’s main activity.

Figure 14. Click the Animate button to run the animation (click to enlarge)


What about using the AVD Manager?

If you’re like me, you might expect it’s possible to change the emulator settings via the AVD Manager. For example, an AVD’s configuration screen has a Graphics drop-down list box with Software - GLES 1.1 (the default) and Hardware - GLES 2.0 entries. I tried selecting Hardware - GLES 2.0, but the change didn’t stick. I successfully changed the hw.gpu entries in the config.ini file.


Running your Android app on a live device

Running an app via a slow emulator can be very frustrating. One solution is to use faster emulation software, such as GenyMotion’s Plugin for Android Studio. Another solution is to use an actual Android device.

Some years ago, I purchased a first-generation Amazon Kindle Fire HD 7" tablet, which runs Android 4.0.3 (API Level 15). I still use this tablet to run Android apps that don’t require the latest Android APIs.

While researching how to use my Kindle Fire tablet with Android Studio 3.2.1, I found two useful guides from Amazon: Set Up Your Development Environment for Fire Tablets and Connect to Fire Tablet through ADB. I’ll summarize the process of connecting a Kindle Fire device to Android Studio, but refer to these guides if you need more information.

First, if you’re a Windows user like me, you’ll need to start by uninstalling the non-ADB driver that’s installed when your Kindle Fire tablet is connected to your development computer, without first enabling ADB. Then you’ll install Amazon’s USB driver.

Next, download the Kindle Fire USB driver. The downloaded ZIP archive contains a Fire_Devices ADB drivers.exe application.

Execute Fire_Devices ADB drivers.exe and follow instructions. I ended up with a C:\Program Files (x86)\Amazon.com\Fire_Devices\Drivers directory containing the necessary driver files.

After installing the drivers, you’ll need to enable ADB on your tablet. Then, you’ll connect the tablet to your development computer. See the Amazon guide if you need additional instructions for connecting your tablet to Android Studio.

Once you have everything set up, start Android Studio, load your Android project, and run the app. This time, the Select Deployment Target dialog box should show an Amazon KFTT entry in the Connected Devices section. Select this entry and click OK. Android Studio responds by directing Gradle to build the app. Once that’s done, it will install the app’s APK and run the app on the device.

Figure 15. Click Animate to perform the animation (click to enlarge)


Conclusion to Part 3

You’ve written, built, and run your first Android Studio application using Android 3.2.1 or higher, and you’ve done some troubleshooting along the way. As a next step, I suggest experimenting with what you’ve learned. Use the examples and source code from the first three Android beginner tutorials to develop a new project of your own. Keep your projects simple while you learn the ins and outs of working with Android Studio and its built-in features, but do challenge yourself to experiment.


Android Studio for beginners, Part 4: Debugging tools and productivity plugins

Use built-in tools and plugins to improve code quality and boost productivity in Android Studio

Android Studio offers a rich palette of built-in development tools, and an even more abundant plugin ecosystem. The first three articles in this series focused on installation and setup and coding and running a simple mobile app with Android Studio. Now you’ll get acquainted with some of the more advanced tools: three built-in tools and three plugins for debugging and improving the quality and productivity of your Android application code.

This article introduce the following tools for Android Studio:

Built-in debugging tools

  • Logcat
  • Debug
  • Lint

Plugins for developer productivity

  • ADB Idea
  • Codota
  • Lombok Plugin

What’s new in Android Studio 3

Find out what to look for in the latest version of Android Studio, including support for Kotlin, Java 8, and a wealth of new tools and plugins.

Logging and debugging Android apps

A buggy app is a sure way to drive away potential customers. Logcat and Debug are two tools that come built-in to Android Studio, which you can use to identify and fix bugs in your Android code.

Logging Android: Logcat

You might not need or want a full-blown debugger for every “buggy” scenario. In some cases it’s sufficient to log and correct the values of certain variables. Android Studio’s Logcat is perfect for this task.

Logcat is a command-line tool (integrated into Android Debug Bridge – ADB) that dumps a log of system messages that can help you find and fix problems in your code. Messages include stack traces for when the device throws an error, and log messages that you’ve purposefully embedded with the android.util.Log class. Logcat is so useful it’s been integrated directly into Android Studio, where you can access it from the View menu or the tool window bar.

Figure 1. The Logcat window reveals a list of date-and-time-stamped system messages (click to enlarge)

The Logcat window is divided into a horizontal row of drop-down lists and other controls followed by a message area. From left-to-right, the controls are:

  • A drop-down list identifying connected devices and emulators. (See Figure 1.)
  • A drop-down list identifying installed APK packages on the selected device.
  • A drop-down list of logging levels:
  • Verbose: show all messages.
  • Debug: show debug log messages that are useful during development only, as well as the message levels lower in the drop-down list.
  • Info: show expected log messages for regular usage, as well as the message levels lower in the drop-down list.
  • Warn: show possible issues that are not yet errors, as well as the message levels lower in the drop-down list.
  • Error: show issues that have caused errors – thrown exceptions, as well as the Assert message level.
  • Assert: show issues that the developer expects should never happen.
  • A search bar where the only messages that appear are those containing the text you type in this control.
  • A check box that lets you use regular expressions in the search bar. For example, in the context of Figure 1, you might specify SystemClock | AlarmManager (i.e., the message must contain either word).
  • A drop-down list for filtering messages, including the following options:
  • No Filters (the default) causes all messages for the selected device to appear, regardless of the selected APK package.
  • Show only selected application presents only those messages for the selected APK package on the selected device, which are of the appropriate log level or lower.
  • Edit Filter Configuration lets you create a custom filter.

In the source code, you can insert calls to various android.util.Log methods to log messages. For example, you might call public static int i(String tag, String msg) to log an INFO-level message, or public static int w(String tag, String msg) to log a WARN-level message.

For either method, the string passed to tag identifies the message’s source (e.g., the method in which this logging method was called), and the string passed to msg identifies the message being logged.

Alternatively, you could call System.out's and System.err's print() and println() methods. Calls to the System.out methods accomplish the same thing as log.i() calls; calls to the System.err methods accomplish the same thing as log.w() calls.

Figure 2. Logging messages in the onCreate() method of the example app’s main activity (click to enlarge)

In Figure 2, the only displayed messages are for the example app process running on the emulated Nexus 5X device. Furthermore, these messages must contain onCreate and be accepted by the Show only selected application filter.


More about Logcat

Check out Google’s “Write and View Logs with Logcat” to learn more about Logcat. Also study the android.util.Log class’s documentation.

Debugging Android: Debug

Using Logcat to log and correct code is okay for very simple apps. For more complicated apps, this form of debugging can be tedious. Instead you’ll want something that lets you debug the app’s executable code. Android Studio’s built-in Debug tool offers many capabilities, including the following:

  • Select a device on which to debug your app.
  • Set breakpoints in your application code (Java, Kotlin, or C/C++).
  • Examine variables and evaluate expressions at runtime.

There are some prerequisites before using this debugging tool:

  1. If your app includes C/C++ source code, you’ll need to install LLDB from the SDK Manager (see Figure 3). Fortunately, the example app for this series (W2A) doesn’t contain C/C++ code, so we can ignore this prerequisite.

Figure 3. Check the LLDB check box and click OK to install LLDB (click to enlarge)

  1. You must enable debugging on a connected device. However, if you’re using an emulator (which we are for this example), you can ignore this prerequisite. Debugging is enabled by default on emulated devices.
  2. You must run a debuggable build variant. By default, this is created for you, so in many cases (including this example) you don’t have to worry about it.

Let’s run through a quick debugging session.


Simple Android debugging

Assuming you’re running Android Studio with the editor window for the example app (W2A.java) open, your first step is to set a breakpoint on the public void onCreate(Bundle savedInstanceState) line. Set the breakpoint by highlighting this line and doing one of the following:

  • Click the gutter area to the left of the line; the line should turn pink in response.
  • Select Toggle Line Breakpoint from the Run menu.
  • Press Ctrl and F8 simultaneously.

Now select Debug ‘app’ from the Run menu, or click the appropriate icon on the tool bar. If the emulator isn’t running, you’ll observe the Select Deployment Target dialog box. I selected Nexus 5X API 15 and clicked OK.

While you’re waiting for the emulated device to come online, click the Debug button on the tool-window bar to display the Debug window. Eventually, you should see something similar to Figure 4.

Figure 4. The Debug window reveals stack frames, current variables with their current values, and more (click to enlarge)

The Debug window provides icons for stepping over, into, and out of a method, and more. Figure 5 shows what happens when we step over a method.

Figure 5. You can step over, into, and out of a method

Click the appropriate icon and select Step Over from the Run menu, or press F8. This lets us proceed deeper into the onCreate() method while stepping over each method call.

Select the line with the closing } character for the onCreate() method, then select Run to Cursor. You’ll receive a notice that the application is running. After unlocking the device, you should see the example app’s activity window.

Figure 6. Click the top three icons to the left of the Debugger tab to resume, pause, and stop the app, respectively (click to enlarge)


More about Debug

Check out Google’s “Debug your app” to learn more about debugging in Android Studio; for example, how to use various kinds of breakpoints.


Debugging with GAPID

While not covered here, I recommend checking out GAPID: Graphics API Debugger, a collection of debugging tools that let you inspect, tweak, and replay calls from an Android app to a graphics driver.

Code inspection with Lint

No matter how carefully you write it, your source code is likely to contain bugs, stylistic issues, and may reference resources that are inactive for one reason or another. A linter is a type of tool that scans source code for evidence of these and other bits of nasty fluff, which it reports to the developer.

Lint is a built-in linter for Android SDK. You can use it to locate issues such as deprecated elements and API calls that aren’t supported by your target API.

To run Lint from within Android Studio, select Inspect Code… from the Analyze menu. Doing so activates the Specify Inspection Scope dialog box.

Figure 7. Setting to inspect the entire project (click to enlarge)

From the dialog box, select the desired scope (entire project, in this case), then click OK to begin the inspection. The results will appear in the Inspection Results window, where they’re organized by category.

Figure 8. Not shown are two spelling mistakes: Lint doesn’t like ‘javajeff’ (click to enlarge)

True to its nature, Lint has picked out a few pieces of fluff that could otherwise clutter the application code. Once spotted, it’s easy to fix the three Java warnings shown in Figure 8: simply declare androidAnimation private and remove the casts from the two findViewById() method calls.


More about Lint

Check out “Improve your code with lint checks” to learn more about using Lint in Android Studio, and to learn about the Android SDK’s standalone Lint tool.

Installing and using Android Studio plugins

While built-in tools have their merit, many other tools are available as plugins. In this section, we’ll look at three plugins for improving the productivity of your coding in Android Studio:

  • ADB Idea
  • Codota
  • Lombok Plugin

Android Studio plugins manager

Android Studio’s plugins manager makes it very easy to find and install plugins. Activate the plugins manager by selecting File > Settings followed by Plugins from the Settings dialog box:

Figure 9. The Settings dialog box shows all installed plugins (click to enlarge)

Next, click Browse repositories… to activate the Browse Repositories dialog box, which presents a full list of supported plugins. We’ll use this dialog to select our first plugin, ADB Idea.

Figure 10. The pane on the right presents detailed information about the selected plugin (click to enlarge)


Boost your Android productivity

Code shortcuts: ADB Idea

ADB Idea speeds up day-to-day Android development by providing fast access to commonly used ADB commands, such as starting and uninstalling an app.

Select ADB Idea in the repository list of plugins, then click the Install button. Android Studio proceeds to download and install the plugin. It then relabels Install to Restart Android Studio. For each plugin, I had to reselect the plugin after clicking Restart Android Studio, and then click this button a second time in order to restart Android Studio.

Figure 11. Install ADB Idea (click to enlarge)

Once installed, Android Studio lets you access ADB Idea from its Tools menu. Select Tools > ADB Idea and choose the appropriate command from the resulting pop-up menu.

Figure 12. Select the appropriate ADB command from the pop-up menu (click to enlarge

After I selected ADB Restart App, I observed the following messages in the Event Log window as well as the restarted app on my Amazon Kindle device.

Figure 13. Each message identifies the app, operation, and device


Find usable code: Codota

You can use the Codota plugin to access the Codota search engine, which lets you look through millions of publicly available Java source code snippets for solutions to Android coding problems.

Figure 14. Install Codota (click to enlarge)

Select Codota in the repository list of plugins and then click the Install button. After Android Studio has downloaded and installed the plugin, it will re-label the Install button to Restart Android Studio. Restarting activates Codota.

Upon restart, you’ll encounter the Codota Authentication dialog box. Click the link and follow instructions to receive the token. Then, paste the token into the aforementioned dialog box and click Go.

Figure 15. Enter the authentication token and click OK (click to enlarge)

Android Studio lets you access Codota by right-clicking on Java code in the editor window and selecting the Get relevant examples menu item, as shown in Figure 16.

Figure 16. Click ‘Get relevant examples’ (click to enlarge)

Clicking this menu item results in the browser presenting a page with relevant code examples. For example, the following page presents examples that are relevant to findViewById:

Figure 17. The browser presents relevant examples for the highlighted findViewById text (click to enlarge)


Autogenerate Java code: Lombok

Project Lombok offers a set of annotations that you can use in place of boilerplate code, thus saving you time writing out this code by hand.

Figure 18. Click Install to install Lombok Plugin (click to enlarge)

Select Lombok Plugin in the repository list of plugins, then click Install. After Android Studio downloads and installs the plugin, it will prompt you to Restart Android Studio. Restarting activates Lombok Plugin.

A simple example will demonstrate Project Lombok’s usefulness. Suppose we add the following minimal Robot class to the example app’s W2A.java source file:

class Robot
{
private String name;
}

The idea with this class is that we’ll store the name of the robot being animated and potentially any other information that might be useful, and display this information as a toast (a small message that appears like a tool tip).

We could take a few minutes to add a constructor and getter/setter methods to this code. However, a better option is to let Lombok add this boilerplate for us. Here are the steps:

  1. Right-click on Robot.
  2. Select Refactor from the pop-up menu.
  3. Select Lombok from the next pop-up menu.
  4. Select Default @Data from the next pop-up menu.

You should now observe an @lombok.Data annotation prefixed to the class Robot header. This annotation causes the constructor, getter/setter methods, and other boilerplate code to be auto-generated. You can see all of this boilerplate by repeating the previous steps, but this time select Delombok instead of Lombok. You’ll see that Lombok has generated something like the following:

class Robot
{
private String name;

public Robot() {
}

public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

public boolean equals(final Object o) {
    if (o == this) return true;
    if (!(o instanceof Robot)) return false;
    final Robot other = (Robot) o;
    if (!other.canEqual((Object) this)) return false;
    final Object this$name = this.getName();
    final Object other$name = other.getName();
    if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
    return true;
}

protected boolean canEqual(final Object other) {
    return other instanceof Robot;
}

public int hashCode() {
    final int PRIME = 59;
    int result = 1;
    final Object $name = this.getName();
    result = result * PRIME + ($name == null ? 43 : $name.hashCode());
    return result;
}

public String toString() {
    return "Robot(name=" + this.getName() + ")";
}

}

Conclusion to Part 4

Android Studio is an amazing (albeit somewhat buggy) environment for developing Android apps. In this short series I’ve showed you how to download and install Android Studio, walked you through a short Android app-development tutorial, showed you how to build and run your app on a device emulator, and introduced you to a number of useful tools and plugins for Android development.

There’s much more for you to learn. For example, you might want to play with Android Profiler to monitor your app’s performance and discover any hidden performance bottlenecks. You might also want to install and explore additional plugins to boost your coding productivity.

I hope you’ll use Android Studio with both its built-in tools and extensible plugin architecture to develop your Android mobile apps.

Originally published by Jeff Friesen, JavaWorld at https://www.javaworld.com

#java #mobile-apps #android

Android Studio for beginners
11 Likes58.65 GEEK