Taxonomy Icon

Mobile Development

This tutorial introduces Android application development with the Android Studio integrated development environment (IDE), including the construction of an example application. The application is a basic starter experience, complete with all phases of building, running and monitoring. While the application has the “basics,” it also demonstrates a key feature of the Android platform-launching another application as it takes user input and passes that information to the mapping application. To get the most from this tutorial, mobile-development experience is helpful, but not required. Java programming skills are required for Android applications, but are not an explicit requirement for this tutorial.

Why do we care about Android? We care about the Android platform because it is the most widely distributed mobile platform on the planet and is accessible to consumers around the globe. In economies where the ownership of a personal computer is a luxury, mobile device usage is the norm-and Android is playing a major role in connecting people to one another. As you will learn in this tutorial, Android takes a distinct approach to applications. The architecture of Android permits a highly customizable software environment thanks to its runtime binding of requested actions and the code to satisfy those requests. Whether it’s market-driven considerations or the technical aspects of Android, it is a platform worth examination. Further, if you are giving serious consideration to having a mobile experience for your platform, you cannot ignore Android.

Prerequisites

This tutorial requires several technologies that work together. You need all of them for this tutorial.

  • Android Studio – Android Studio is the primary starting point for constructing Android Applications
  • Android device or Emulator – You will want either a physical Android device, or the Android Emulator. Either way, reading through this tutorial will aid you in understanding the basic connection points of an Android application.
  • Source code – Source code snippets in this tutorial include:

    • AndroidManifest.xml snippet – This file is the application deployment descriptor for Android applications.
    • MainActivity.java – This implements an Android activity, the primary entry point to the sample application of this tutorial.
    • Activity_main.xml – This contains definitions for the visual elements, or resources, for use by Android activities.
    • AndroidManifest.xml complete – This lists a full AndroidManfest.xml file, along with a description of each of the important elements.

Introducing the Android architecture

Before diving right into the ins and outs of the Android Studio and developing Android applications, let’s have a look at the architecture of Android and some of the key terms that will be helpful in the tutorial and beyond, as you begin to build Android applications for yourself.

Android terminology

An understanding of the terms below is helpful in Android application development with Android Studio.

  • Android is an open source operating environment targeted for mobile devices. Increasingly, Android is found in applications beyond &smartphones&. These include wearable technology, appliances such as projectors, speakers and televisions, and even automobiles.
  • Emulator is a software tool representative of another system. Often, an emulator is an environment that runs on a personal computer (PC, Mac, Linux machine) that emulates another environment, such as a mobile-computing device.
  • Linux is an open source operating system kernel at the heart of many computing platforms, including servers, desktop computers, networking appliances, and mobile-computing devices. Android runs on top of a Linux kernel.
  • Android Run Time (ART) is an operating environment found in the Android stack, which executes application code at runtime. The Android Run Time replaces the &legacy& Dalvik Virtual Machine (VM) from earlier versions of Android which operated in a manner similar to a compliant Java VM.

The intent

Since its inception, Android has become a dominant force in the mobile phone space. Its application model is unique in that applications are not monolithic, menu-laden applications that require a great deal of clicking and tapping to operate. Sure, there are menus and buttons to be tapped, but Android has an innovative design element to its architecture known as an intent.

An intent is a construct that permits an application to issue a request, which is somewhat like a help-wanted sign. It might look like these:

  • “Wanted: An application to help me look up a contact”
  • “Wanted: An application to help me display this image”
  • “Wanted: An application to perform this geographic-based search.”

In a similar and complementary fashion, applications can register themselves as capable and interested in satisfying various requests or intents. To follow the classified advertising paradigm, these might look like this:

  • “Available: Application ready and willing to present contact records in clear, concise manner”
  • “Available: Application ready and willing to perform a geographic search.”

These are examples of IntentFilters, which are discussed next.

The IntentFilter

Applications announce their availability to perform these types of operations via a construct known as an IntentFilter. The IntentFilter is either registered at runtime or is enumerated in the AndroidManifest.xml file. The following snippet comes from an Android application that responds to incoming SMS (text) messages:

<receiver android:name=".MySMSMailBox" android:exported=&true&>
     <intent-filter>
       <action android:name="android.provider.Telephony.SMS_RECEIVED" />
     </intent-filter>
 </receiver>

After this brief introduction to the intent and IntentFilter, the next section introduces the four main types of Android applications.

Types of Android applications

Let’s take a moment to examine the four main types of Android applications:

  • Activity
  • Service
  • Receiver
  • ContentProvider

We will also take a look at the views to display the user-interface (UI) elements.

Activity apps

The activity is the most visible and prominent form of an Android application. An activity presents the UI to an application, along with the assistance of a class known as a view. The view class is implemented as various UI elements, such as text boxes, labels, buttons, and other UIs typical in computing platforms, mobile or otherwise. An application may contain one or more activities. An activity is typically defined on a one-to-one relationship with the screens found in an application.

An application moves from one activity to another by calling a method known as startActivity() or startSubActivity(). The former method is used when the application desires to simply “switch” to the new activity. The latter is used when a synchronous call/response paradigm is desired. In both cases, an intent is passed as an argument to the called method.

It is the operating system’s responsibility to determine the best-qualified activity to satisfy the specified intent.

Service and receiver apps

Like other multi-tasked computing environments, there are applications running “in the background” that perform various duties. Android calls these types of applications services. The service is an Android application that has no UI.

The receiver is an application component that receives requests to process intents. Like the service, a receiver does not, in normal practice, have a UI element. Receivers are typically registered in the AndroidManifest.xml file.

The following snippet (which is the same as the one shown for IntentFilter) is an example of a receiver application being defined. Note that the name attribute of the receiver is the Java class responsible for implementing the receiver.

<receiver android:name=".MySMSMailBox" android:exported=&true&>
     <intent-filter>
       <action android:name="android.provider.Telephony.SMS_RECEIVED" />
     </intent-filter>
 </receiver>

The following snippet is an example of receiver code:

package com.navitend.samplereceiver;

import android.content.Context;
import android.content.Intent;
import android.content.IntentReceiver;

public class myreceiver extends IntentReceiver
{
    public void onReceiveIntent(Context arg0, Intent arg1)
    {
        // do something when this method is invoked.
    }
}

ContentProvider apps

The ContentProvider is the Android mechanism for data-store abstraction. Let’s look at a specific type of data found on a mobile device: the address book or contacts database. The address book contains all the contacts and phone numbers a person might require when using a mobile phone.

The ContentProvider is a mechanism to abstract access to a particular data store. In many ways, the ContentProvider acts in the role of a database server. Operations to read and write content to a particular data store should be passed through an appropriate ContentProvider, rather than accessing a file or database directly. There may be both “clients” and “implementations” of the ContentProvider.

Android Views

Android views are the UI mechanism for putting things on the screen of an Android device. The Android activity employs views to display UI elements. Some of the more popular layout designs include:

  • LinearVertical – Each subsequent element follows its predecessor by flowing beneath it in a single column.
  • LinearHorizontal – Each subsequent element follows its predecessor by flowing to the right in a single row.
  • Table – A series of rows and columns, similar to an HTML table. Each cell can hold one view element.
  • Constraint – Each element is &constrained& to an aspect of the display such as the top or side of the screen or another element. This layout aids in the construction of &responsive& applications and is the heir-apparent to the legacy Relative Layout introduced in earlier versions of the Android platform.

After a particular layout (or combination of layouts) has been selected, individual views are used to define the UI.

View elements consist of familiar UI elements, including:

  • Button
  • ImageView
  • EditText to gather input with various filters such as Date or Numeric
  • TextView (similar to a label, displays static text)
  • CheckBox
  • Radio Button
  • Spinner (similar to a &drop-down& combo box)
  • AutoComplete (EditText with auto text-complete feature)

Views are defined in an XML file. For example, this shows a simple LinearVertical view, with buttons and textviews defined:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Activity 1!"
    />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Activity 1, second text view!"
    />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Switch To Activity 2"
    id="@+id/switchto2"
    />
</LinearLayout>

Note that each element has one or more attributes in the android name space.

The next section walks through obtaining the Android SDK and configuring it for use with Android Studio.

Getting started with Android Studio

Now that we have a feel for the components of the Android platform, let’s get started with Android Studio. This section walks through obtaining Android Studio and a discussion of the numerous versions of the Android SDK.

Obtaining and installing Android Studio

This first step is very straight-forward. Open your web browser to https://developer.android.com/, and scroll down to download Android Studio. Android Studio is available for Windows, Mac, and Linux.

Android Studio is based on the IntelliJ IDE platform. If you’re the kind of developer who is interesting in leveraging keyboard shortcuts, you might consider learning more about IntelliJ from the jetbrains website.

Getting started with the Android SDK

Now that we have Android Studio installed, it is time to get the Software Developer Kit (SDK) for Android.

But, before we go any further, we need to have a discussion around Android versions.

Android versions

Since its inception, Android has been released under a somewhat parallel path of numeric release revisions, API levels, and also “sweet” names including Jelly Bean, KitKat, Oreo, and other confectionary favorites.

It is easy to be overwhelmed by the choices available. For now you need just a little bit of understanding of this &version landscape& to get started as an Android developer.

There are many versions, or revisions, of Android in the wild. If you are going to write an application for commercial release, you will need to know which devices you are targeting. Wikipedia has a nice summary of the Android versions, the names, the release dates as well as a graphic depicting the approximate number of each device in the marketplace.

Newer devices run the latest code, and older devices can be somewhat constrained in their ability to upgrade to a newer version of Android. Sometimes the newer versions support capabilities that the older handsets are not capable of supporting (think second camera, Near Field Communications, and so on). Another non-trivial reason that older handsets may not be able to run the latest Android version is that both the manufacturer and the telecom carrier (Verizon, AT&T, and so on) need to support the software running within their ecosystem. Supporting a new operating system requires resources on the part of the device manufacturer and the carrier. Market forces suggest that these market participants are more concerned with future sales than supporting prior sales and invest their human capital accordingly.

As a software developer, what does it matter that there are new versions of the operating system? This breaks down into two broad categories when it comes to programming applications:

  • A new version of the operating system often introduces new features which we can take advantage of and/or our user base expects our applications to support.
  • Older (or legacy) features of the environment may be actually hindering newer features and/or represent an inferior approach to providing a specific set of functionality. Sometimes code needs to actually be removed from the API definitions. There is a special term for this &removal& of formerly working code – we call it &code deprecation&. When an API has been marked for removal, we say that this is a deprecated API. This is essentially a message to the developer that goes something like this: &Warning& this code will be removed in the future, please plan accordingly.&

The Android platform has been fairly liberal (that is, favorable to the developer) with its approach to deprecated code by permitting applications to continue using older APIs for quite a while after being marked as deprecated. (This approach contrasts with Apple’s approach with deprecated code in iOS where older code can simply just stop working on the next OS release. With iOS, even the programming language seems to change while we are not looking!)

While Android may be a bit more forgiving with its long-suffering of deprecated code, we do need to keep an eye on the documentation tag which says that a particular API is deprecated. If some code that we’re using is marked as deprecated, we will need to eventually change our approach in a future version of our application because any API which is marked as deprecated can be removed in a future release. Deprecation markers in the SDK are our roadmap to future opportunities for improvement and for potential headaches. Sometimes the “new” way of doing things is simple and straight-forward, but not in every case!

Being a successful mobile application developer requires an ongoing investment over the lifetime of an application where time tends to pass like dog years…very quickly!

With this basic intro to the versions of Android, it’s time to obtain the Android SDK.

Obtaining and installing the Android SDK

Start Android Studio. Under the Tools menu, select SDK Manager. This menu option loads the Android Studio Preferences dialog and pre-selects the Android SDK sub menu. This menu is our primary means of interacting with the various SDKs available for the many versions of Android.

Screen shot of Android Studio Preferences dialog, with the Android SDK Manager listing the available versions of the Android SDK

With each release of the operating system, the API level increments. Notice that the revision increases slower than the API level. You can think of the revision as a “generation” of the platform, or as a “Major” version number. When you browse the Android documentation, be sure that you note which API level that a particular capability was introduced. Each API is available at the API Level indicated and greater, unless the API has been deprecated and subsequently removed. For example, the ContactsContract API was introduced at level 5, which is quite “old” at this point.

Select one or two SDK levels to work with for now. The SDK Manager will subsequently download the related files and make them available for use within Android Studio.

Also under the Tools menu is an option for the AVD Manager. AVD stands for Android Virtual Device. This is the emulator. The emulator is helpful because it permits us to test applications on various device types, sizes, and versions. The screen shots in this tutorial are taken from the emulator. More on this later.

Building your first Android application

This tutorial steps you through creating a basic Android application, called SaySomething, using Android Studio and demonstrating it on the Android emulator.

Step 1: Create a new project

  1. Select File > New Project.
  2. Fill out the Create Android Project dialog, and click Next.

    Screen shot of Create New Project dialog in Android Studio

    The requirements for the new project include:

    • Application name
    • Company domain (this gets reversed into com.domain) to keep applications partitioned even if they have the same Application name.
    • Project Location – where to store the files
    • The Package name is suggested from the Application Name and Company domain
    • By default, Android applications are written in Java. If you want to support alternate languages, such as C++ (for native code) or Kotlin, select the appropriate check boxes.
  3. On the Target Android Devices dialog, specify the API level and target platforms. As mentioned earlier, Android is for more than just phones, though for our purposes we will simply select the Phone and Tablet form factor for this tutorial. Then, click Next.

    Screen shot of Target Android Devices dialog in Android Studio

  4. On the Add an Activity to Mobile dialog, select the Empty Activity type. Then, click Next.

    Screen shot of Add an Activity to Mobile dialog in Android Studio

    This will create a default application ready to be built and run directly from Android Studio.

  5. On the Configure Activity dialog, name the files for the application.

    Screen shot of Configure Activity dialog in Android Studio

Step 2: Review the code

The following figure shows the components of our new project:

Screen shot of New Project files shown in the Project section of Android Studio

There are two folders: app and Gradle Scripts.

  • The app folder contains all of our application’s code.
  • The manifests folder in the app folder contains AndroidManifest.xml which is the deployment descriptor for this application. This file tells the Android device about how to interact with the application, which Activity to show when the application is started, which Intents the application services, which icons to display and much more.
  • The java folder contains the source code for the application. In this case, the file which implements our activity plus a couple of class files for performing automated tests (which we will ignore for this tutorial).
  • The res folder contains the resources for the application, including icons, layout files, strings, menus, and so on.
  • The Gradle Scripts folder contains all of the scriptable elements for building the application. The Gradle build system is a topic unto itself. For now, understand that these scripts govern the process of building the application – and importantly for more mature projects and teams, each of these steps is able to be run from the command line. This is important because this approach supports automation and fall into the category of Continuous Integration.

Now, let’s examine the source code in further detail.

Primary activity for the application

Our sample application consists of a single activity, named MainActivity.

package com.navitend.saysomething;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

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

        Log.i("IBM","Hello there logcat!");

        setContentView(R.layout.activity_main);

        final Button btnHitMe = (Button) findViewById(R.id.hitme);
        final Button btnMapMe = (Button) findViewById(R.id.mapme);
        final TextView tvLabel = (TextView) findViewById(R.id.thelabel);
        final EditText etLatitude = (EditText) findViewById(R.id.etLatitude);
        final EditText etLongitude = (EditText) findViewById(R.id.etLongitude);

        btnHitMe.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tvLabel.setText("Ouch!");
                }

            }
        );

        btnMapMe.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    String coords = etLatitude.getText()+","+etLongitude.getText();
                    Log.i("IBM",coords);
                    Uri mapsIntentUri = Uri.parse("geo:" + coords);

                    Intent mapIntent = new Intent(Intent.ACTION_VIEW, mapsIntentUri);

                    startActivity(mapIntent);
                }
            }
        );
    }
}

Things to note about this source snippet:

  • MainActivity is a normal Java class, with a package and imports, as expected.
  • MainActivity extends a base Android class named AppCompatActivity, which is located in the package named android.support.v7.app.
  • The onCreate() method is the entry point to this activity, receiving an argument of type Bundle. The Bundle is a class which is essentially a wrapper around a map or hashmap. Elements required for construction are passed in this parameter.
  • The setContentView(..) is responsible for creating the primary UI using the R.layout.main argument. This is an identifier representing the main layout found in the resources of the application. Note that any identifiers in the “R” class are automatically generated by the build process. Essentially all of the xml resource files under the res folder described earlier are accessed with the R class.

Resources for the application

Resources in Android are organized into a subdirectory of the project named res, as described previously. Resources fall into a number of categories. Three of these categories are:

  • Drawables – This folder contains graphics files, such as icons and bitmaps
  • Layouts – This folder contains XML files that represent the layouts and views of the application. These will be examined in detail below.
  • Values – This folder contains a file named strings.xml. This is the primary means for string localization for the application. The file colors.xml is useful for defining color codes used by the application. This file is analogous to a css style sheet for those familiar with web programming techniques.

Primary UI resources in the main_activity.xml file

The sample application contains a single activity and a single view. The application contains a file named main_activity.xml that represents the visual aspects of the primary UI of the activity. Note that there is no reference in the main_activity.xml where the layout is used. This means it may be used in more than one activity, if desired. See the following code listing

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center_vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="301dp">

        <Button
            android:id="@+id/hitme"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hit Me!"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            tools:layout_editor_absoluteY="383dp" />

        <Button
            android:id="@+id/mapme"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Map Me!"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            tools:layout_editor_absoluteY="460dp" />

    </LinearLayout>

    <TextView
        android:id="@+id/thelabel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Hello World, Say Something!!!!!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/etLatitude"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Latitude"
        android:inputType="numberDecimal"
        android:text="40.9241164" />

    <EditText
    android:id="@+id/etLongitude"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Longitude"
    android:inputType="numberDecimal"
    android:text="-74.7213913" />

</LinearLayout>

This is an example of a fairly straight-forward layout. There is a single linear layout, which is oriented as a vertical layout, meaning all contained elements are in a single column. Within this encapsulating LinearLayout, there is a second LinearLayout organized as a horizontal layout. This inner layout contains a pair of button widgets. Below the horizontal LinearLayout there is a single TextView element, which can be likened to a label in other development environments. A TextView represents static text that is not editable. Below the TextView, there are two EditText widgets, configured to take numeric inputs. These input elements are used to capture a Latitude and Longitude value which will subsequently be passed along to a mapping application, as demonstrated below.

Note that each view element has attributes in the android name space. Some attributes are common to all views – the android:layout_width and android:layout_height attributes, for example. The values available for these attributes are:

  • Match Parent – This extends the view element to take the maximum space available. This can also be thought of as meaning “stretch.”
  • Wrap Content – This option results in the element expanding just enough to contain its child views or attributes such as text or image.

Deployment descriptor for an Android application (AndroidManifest.xml)

The AndroidManifest.xml file represents the deployment descriptor for an Android application. The file lists any activity, service, content provider, or receiver contained in the application, along with the appropriate IntentFilters supported by the application. Here is the complete AndroidManifest.xml file for the sample application:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.navitend.saysomething">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Things to note about the AndroidManifest.xml file:

  • The package name from the source file is represented here. This follows a similar pattern to a Java source file and imports. The <manifest> tag is in essence importing classes from this package. All non-fully qualified classes in this file are found in the package identified in the package attribute.
  • The <application> tag has an attribute that references a resource from the application’s resources. Note the @ symbol preceding the various identifiers. This is a hint for the toolchain to look in the respective folder of the application’s resources for each resource.
  • The <activity> tag contains the following attributes and values of note:

    • android:name represents the Java class implementing this activity
    • android:label contains the name of the application. Note that it is referencing one of the string resources. The string.xml file contains localized strings for the application.
    • <intent-filter> represents the IntentFilter available in the sample application. This specific set of action and category attributes are the most common IntentFilter seen in Android applications. This filter essentially says that it implements the main action (or entry point) and is available in the currently operating launch screen for the OS. In simple terms, this means it can be started as an application from the primary list of applications on an Android device.

Step 3: Build the application

To build the application, select the wrench icon (looks more like a hammer to me) in the menu of Android Studio.

The build process, as introduced earlier, is a multi-step process that may be customized for any particular application. For this tutorial, we do not modify the build process. The output of the build process should look something like this:

Screen shot of Build Output in Android Studio

To demonstrate the build process, we have introduced an error into the source code; we added an extra space in the name of the method findViewById, shown in the following figure:

Screen shot of intentional error in source code

This creates a syntax or parsing error which is picked up by the build process and displayed in the details of the build results window in Android Studio. Upon fixing the error in the source code, the application builds properly, and the errors are removed from the problems list.

Step 4: Run the application

Now that the application has compiled successfully, it’s time to run the sample application.

Earlier in this tutorial the AVD Manager was introduced as the means for configuring the emulator for testing applications without the need for a real device. Running an application by using the emulator is particularly useful because it permits testing without the need to purchase numerous costly devices.

To setup an emulator, or more properly, an Android Virtual Device (AVD), select Tools > AVD Manager. Or, simply click on the Play (Run) icon.

This launches a window that lets you select either a real device that is connected by a USB cable or an available AVD instance, as shown in the following figure:

Screen shot of the Select Deployment Target dialog and the Create New Virtual Device circled

If there are connected devices, each shows up in the drop-down below Connected Devices. Alternatively, select from one of the available Virtual Devices. In the previous figure, there is a single AVD defined entitled Nexus One API P. To create a new AVD, select the Create New Virtual Device button.

Finally, click OK to launch the application on the selected deployment target. The AVD or emulator launches with our sample application running on it.

Screen shot of the sample app running in the emulator or AVD

Step 5: Test the application in the emulator

Now that the application is running on the emulator, let’s have a look at what is happening behind the scenes. Within Android Studio, select View > Tool Windows. We will highlight just a couple of these tool options, though each of them is a topic unto itself.

Android Studio Tools

First, look at the Android Profiler which depicts a running chart of CPU, Memory, and Network traffic. The Android Profiler permits us to toggle between different devices/emulator instances and respective running processes. The following figure displays the metrics for our sample application running on an emulator instance.

Screen shot of the Android Profiler for the running sample app

Logging is a useful tool for any developer on any platform. For Android developers, the name of the tool is LogCat.

The LogCat is a running log file of activity taking place in the VM. Applications can make their own entries to this list with a simple line of code as follows: Log.i(tag,message);1, where tag and message are both Java strings. The Log class is part of the android.util.Log package.

Screen shot of the LogCat for the running sample app

Another useful tool is the file explorer, which permits file system access of the Emulator. The following figure shows where the tutorial’s sample application is deployed on the Emulator.

Screen shot of the Device File Explorer

User applications are deployed in /data/app while Android built-in applications are found in the /system/app directory.

Full-scale debugging of an Android application is beyond the scope of this tutorial, though rest assured that Android Studio supports all of the modern application debugging tools we can hope for with things like Stepping In and Stepping Over function calls.

Testing the sample application

Tap on the Hit Me! button, and the contents of the label changes to “Ouch!”

Screen shot of the sample app in the emulator after tapping the Hit Me button

Tap on the Map Me! button, and a mapping application is launched with the specified latitude and longitude that is contained in the EditText widgets.

Screen shot of the sample app in the emulator after tapping the Map Me button

The wiring of the buttons is in the MainActivity.xml code. In particular, note how the latitude and longitude values are extracted and packaged into an Intent, which is subsequently used to launch the mapping application.

Summary

This tutorial introduced the Android platform, the Android Studio, and the key elements of Android development. You should now be ready to create your own Android applications.