3 Introduction to the Android – A DIY Smart Home Guide: Tools for Automating Your Home Monitoring and Security Using Arduino, ESP8266, and Android

CHAPTER 3

Introduction to the Android

THIS CHAPTER COVERS THE ANDROID MOBILE operating system and related devices. I first start off discussing what Android actually is and I cover some basic concepts concerning Android cell phones. Next, I discuss the system requirements of the main program that is currently used to develop Android applications which is called Android Studio. I then give a quick start guide tour of the key features of Android Studio you will need to use in order to create your own programs. Next, I give the reader a basic overview of the Java language that is used to create Android applications. I cover key Java concepts such as data types, program flow control statements, and classes. Then, I cover the Activity class and the Activity class life cycle that are key to understanding the basic Android application. Next, I present a hands-on example which is an exercise on how to create a program using the Android Studio, modify this program, and run it on an Android device. Finally, I discuss some information on how to import an Android Studio project from an older version of Android Studio to a newer version.

What Is Android?

Android is a mobile operating system that is popular on cell phones and tablets. Android is based on the free operating system Linux and other open-source components. There are also other variations of this operating system such as Android TV for televisions, Android Auto for cars, and Wear OS for wrist watches. Other versions of the Android operating system have been developed for game consoles, digital cameras, PCs, and other electronic devices.

In terms of Android cell phone service there are two general types to choose from which are prepaid and postpaid. Prepaid service involves paying before using any cell phone minutes, text messages, or Internet data. In a prepaid service once all the credit allocated for minutes, text messages, and Internet data have been used up then the cell phone service either stops or is reduced. For example, if you run out of credit on a prepaid plan then phone and text message service may stop but Internet data may continue at a reduced speed depending on the policy of the specific carrier. For a prepaid plan there is no credit check or transmission of personal data such as your identity, address, social security number and no long-term or short-term contracts. Thus, it is a more secure and private way of obtaining cell phone service on demand only when you need it. Also, most prepaid plans offer prepaid cards which can be bought for cash at a local store so that even people without access to credit cards can get prepaid phone service. For a postpaid account, you pay each month for the amount of calling minutes, text messages, and Internet data you have used. This type of account generally requires a credit check, and perhaps requires a valid credit card to be used to fund the account.

A mobile network operator (MNO), which is also called a wireless service provider or wireless carrier, owns the required radio frequencies and cellular infrastructure in order to provide cell phone services to users. Some examples of these MNOs are Verizon, AT and T Mobility, T-Mobile, Sprint Corporation, and U.S. Cellular. A mobile virtual network operator (MVNO) buys cell phone services from an MNO that actually owns the wireless cell phone infrastructure in bulk and resells these cell phone services to consumers in their own custom plans and custom prices. Some examples of MVNOs are Boost Mobile, Cricket Wireless, Liberty Wireless, Mint Mobile, Patriot Mobile, Simple Mobile, Tello, and Ting. The biggest advantage of using these virtual network operators is that the cost of cell phone service can be dramatically lower and also much more flexible. For example, some MVNOs like Tello offer a no contract, prepaid, pay as you go plan where you can put money into your account and are only charged for the calling minutes, text messages, and data you actually use. This credit has no expiration date but you must use some credit after a certain period of time in order to keep your account open and active. For example, you can put $25 into your Tello pay as you go account and link your Android cell phone to it. You can use this Android cell phone in combination with an Arduino, ESP-01, and a motion sensor to provide an affordable burglar alarm system with no monthly fees. The only fees would be for such things like text messages that would notify you that the burglar alarm has been tripped. This would be charged on a per text message basis. Thus, this book can help you build a Do it Yourself (DIY) alternative to the high priced home security systems offered by commercial alarm companies.

The official android web site is located at https://www.android.com/.

Developing Programs for the Android Mobile Operating System

Programs for the Android platform are written in Java. The most current development tool for the Android is called Android Studio. The Android Studio program is available for the Windows, Mac, and Linux platforms.

The official android web site for developers is located at https://developer.android.com/.

The web page for downloading Android Studio is located at https://developer.android.com/studio/.

Android Studio Windows 7, 8, and 10 System Requirements

The current version of Android Studio runs on Windows 7, 8, and 10. The following are the system requirements:

   Microsoft Windows 7/8/10 (32- 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 + 1.5 GB for Android SDK and emulator system image)

   1280 × 800 minimum screen resolution

   Java Development Kit (JDK) 8, however, the use of the bundled OpenJDK (version 2.2 and later) is recommended

Android Studio Windows XP System Requirements (Version 1.5 of Android Studio)

The current version of Android Studio does not support the Windows XP operating system. However, a previous version of Android Studio which is 1.5 supports Windows XP and is still available for download from Google. The following are the system requirements for version 1.5 of Android Studio:

   3 GB RAM minimum, 4 GB RAM recommended

   500 MB disk space, at least 1 GB for Android SDK, emulator system images, and caches

   JDK 7 or higher

   1280 × 800 minimum screen resolution

The Win XP compatible Android Studio version 1.5 download link is http://dl.google.com/dl/android/studio/install/2.1.2.0/android-studio-bundle-143.2915827-windows.exe.

Android Studio Mac System Requirements

   Mac OS X 10.10 (Yosemite) or higher, up to 10.13 (macOS 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 + 1.5 GB for Android SDK and emulator system image)

   1280 × 800 minimum screen resolution

Android Studio Linux System 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 + 1.5 GB for Android SDK and emulator system image)

   1280 × 800 minimum screen resolution

Android Studio Overview

This section will discuss the Android Studio Integrated Development Environment (IDE). Since the Android Studio program is constantly being updated and new versions are being released, the screen captures in this section may not be exactly like the version of Android Studio you are using. So far in 2018 there have been at least six different versions of Android Studio that have been released. In previous years there have been a similar if not greater number of releases. The general appearance of Android Studio is shown in Figure 3-1.

Figure 3-1   The Android Studio Integrated Development Environment (IDE).

The Project Tab

The Project tab in the Android Studio IDE displays the current Android project. The exact format that the project is displayed in depends on the drop-down selection box located to the right of the tab. The default format is “Android” and shows the current project categorized under two main headings which are “app” and “Gradle Scripts.” Under the “app” heading you have the “manifests,” “java,” and “res” directories. The manifests directory contains the Android program’s manifest which specifies such things as permissions that are granted to the program and the minimum Android operating system that is required to run the program. The Java directory contains the program’s source code which is written in the Java programming language. The res directory holds things like the layout of the graphical user interface of the program and the layout of the menus in the program. The “Gradle Scripts” directory holds files that are used to build the final Android program. See Figure 3-2.

Figure 3-2   The Project tab.

Source Code Area

The Arduino Studio has an area where source code can be displayed and edited. In Figure 3-3 the source code area is highlighted by a rectangle and the corresponding source code in the Project tab is circled. You can easily bring up a specific source code file by double clicking on it in the Projects tab. You can select from multiple source code files in the source code by clicking on the corresponding tab.

Figure 3-3   The source code area of the Android Studio.

The Structure Tab

The Structure tab is below the Project tab and displays the functions and variables in the source code file that are currently selected in the source code area. When you click on a function or variable in the Structure tab window the corresponding function or variable within the source code file is displayed. See Figure 3-4.

Figure 3-4   The Structure tab.

The Android Monitor

The Android Monitor tool can be used to monitor the information messages, error messages, warning messages, and debug messages being output from the Android device using the logcat tab. Under the Log Level drop-down list box you can select the type of output you want such as verbose, debug, info, warn, error, or assert. See Figure 3-5.

Figure 3-5   The Android Monitor.

You can also capture a screen shot of an Android device, or record a video from an Android device, using Android Monitor. Just press the screen capture icon which is a picture of a camera on the left-hand side of the Android Monitor window to capture a screen shot of the Android device. See Figure 3-6.

Figure 3-6   Screen shot of Android device using the screen capture feature of the Android Monitor.

If you want to record the Android screen in the form of a movie then press the screen record icon that is located just below the screen capture icon on the left-hand side of the Android Monitor.

The Gradle Console

Gradle is an open-source build tool that Android Studio uses to compile Java programs to a form the Android operating system can understand. Initially, you will need an Internet connection to download key gradle components. Later you can switch gradle to an offline mode and use a local copy of gradle for building your Android application. The Gradle Console is a window in Android Studio that displays the current progress of building the final Android program from Java source code. See Figure 3-7.

Figure 3-7   The Gradle Console.

Viewing the Tools

The Android Monitor window, project window, structure window, and Gradle Console that we have discussed previously can all be selected and viewed under the View->Tools Windows menu selection. See Figure 3-8.

Figure 3-8   Viewing the tools.

Cleaning and Rebuilding the Project

Under the build menu we have the menu selections for cleaning the project and rebuilding the project. The “Clean Project” and “Rebuild Project” menu items are highlighted in Figure 3-9.

Figure 3-9   Compiling the Android program.

Running the App

To actually transfer the final compiled program to your Android device and then run it you will need to select the Run->Run ‘app’ menu item. See Figure 3-10.

Figure 3-10   Running the app.

Setting Up Gradle to Work Offline

By default gradle must use the Internet frequently when you build a project. However, you can select an offline mode to force gradle to use a local gradle distribution on your computer instead of the Internet. Select the File->Settings menu item. This brings up the Settings window. Select “Use local gradle distribution” by clicking on the button next to the item. Select “Offline work” by checking the checkbox next to this item. See Figure 3-11.

Figure 3-11   Setting up gradle for offline use.

Android Device Monitor

The Android device monitor window can be brought up by selecting Tools->Android-> Android Device Monitor from the main menu. Using the Android device monitor you can view the files and the directories that are on the Android device itself as well as upload and download files to and from the device. For example, you can upload an Android APK file to your Android device using the Android device monitor function and then install that APK by double clicking on it from the Android device like you would any other APK file that was downloaded from a web site. The Android device if it is connected to your development system is shown under the “Devices” sub window of the Android device monitor. The files and directories that are on the Android device are displayed under the “File Explorer” tab. See Figure 3-12.

Figure 3-12   The Android device monitor.

Java Language Overview

Java is the programming language that is used to create programs that run on Android-based cell phones and tablets. This section is meant to be a quick overview of the Java programming language and not a reference guide. It would be helpful if you have had experience with other programming languages like C and C++ also.

Java Comments

Java comments are exactly the same as C and C++ comments. Java comments can be in the form of single-line comments or multi-line comments.

   Single-line comments begin with two slash characters “//”.

// This is a single-line C/C++ and Java comment.

   Multi-line comments begin with a slash followed by an asterisk “/*” and terminate with an asterisk followed by a slash “*/”.

Java Basic Data Types

This section covers the different data types available in the Java programming language for Android.

   byte. A byte is an 8-bit number with values between −128 and 127, inclusive.

   short. A short is a 16-bit number with values between −32,768 and 32,767, inclusive.

   int. An integer is a 32-bit number with values between −2,147,483,648 and 2,147,483,647, inclusive.

   long. A long is a 64-bit number with values between −9,223,372,036,854,775,808 and 9,223,372,036,854,775,807, inclusive.

   float. A float is a single-precision 32-bit IEEE 754 floating-point number.

   double. A double is a double-precision 64-bit IEEE 754 floating-point number.

   char. A char is a single 16-bit Unicode character that has a range of '\u0000' (or 0) to '\ uffff' (or 65,535, inclusive).

   boolean. A boolean is a data type that has a value of either true or false.

Java Arrays

In Java, just like in C and C++, you can create arrays of items of the basic data types listed in the previous section. However, the format of an array in Java is very different than in C and C++. The general format of an array declaration is as follows:

An example of an array of floating point numbers that is 16 elements long is:

float[] FloatArray = new float[16];

An example of an array of bytes that is declared to be empty is:

byte[] m_PhotoData = null;

An example of an array of String objects that is m_MaxFileNames long is:

Java Data Modifiers

Java data modifiers allow you to control how variables in a class are accessed and stored.

They include the following:

   private. The private modifier makes variables only accessible from within the class they are declared in. The following declares FloatingPointNumberArray to be private array of eight elements and only accessible from within its own class:

   public. The public modifier allows variables to be accessed from any class. The following variable called PublicArray is an array of 23 floating point numbers:

   static. The static modifier ensures that the variable has only one copy associated with the class they are declared in. The following variable called StaticData is declared as a static floating point array with five elements.

   final. The final modifier indicates that the variable will not change. This is similar to the const keyword in C/C++. For example, the following declares the variable AppName is of type String. It is initialized to “WifiServerApp1” and declared final so that it cannot be changed by other parts of the program.

final String AppName = "WifiServerApp1";

Java Operators

In this section, we cover the basic Java operators that are needed for a useful Java program. These include operators that perform arithmetic, unary operators that only have one argument, conditional operators that are used with program flow control statements, and operators that work on a variable at the bit level. Most of these operators are exactly the same as their C and C++ counterparts.

Java Arithmetic Operators

The arithmetic operators are used to add, subtract, multiply, divide, and find the remainder of two numbers or objects and are exactly the same as in C or C++.

   +. The plus sign adds together two numbers and is also used by the String class to concatenate two different String objects.

   . The minus sign subtracts one number from another.

   *. The asterisk sign multiplies two numbers together.

   /. The slash sign divides one number by another.

   %. The percent sign finds the remainder of a division operation.

Java Unary Operators

Java unary operators are exactly the same as in C and C++.

   −. The minus sign in front of a variable or expression negates that variable or expression.

   ++. Two plus signs next to a variable increment the value of that variable by 1.

   −−. Two minus signs next to a variable decrement the value of that variable by 1.

   !. An exclamation point inverts the value of a boolean variable.

Java Assignment and Logical Operators

The assignment and logical operators for Java are exactly the same as in C and C++. The operators in this section have two operands, one on the left side of the operator and another on the right side of the operator.

   &&. An expression with two ampersands indicates a logical “AND” and evaluates to true if both operands are true and evaluates to false if either operand is false.

   ||. An expression with two pipes indicates a logical “OR” and evaluates to true if either operand is true and evaluates to false if both operands are false.

   =. The equal sign is the assignment operator that assigns the value on the right of the equal sign to the variable to the left of the equal sign.

   ==. An expression with two equal signs is a logical equality test and returns true if the two operands are equal and false otherwise.

   !=. An expression with an exclamation point followed by an equals sign evaluates to true if the operand on the left is not equal to the operand on the right.

   >. An expression with a greater than sign evaluates to true if the operand on the left is greater than the operand on the right and false otherwise.

   >=. An expression with a greater than sign followed by an equal sign evaluates to true if the operand on the left is greater than or equal to the operand on the right.

   <. An expression with a less than sign evaluates to true if the operand on the left is less than the operand on the right.

   <=. An expression with a less than sign followed by an equal sign evaluates to true if the operand on the left is less than or equal to the operand on the right.

Java Bitwise and Bit Shift Operators

   ~. This is the unary bitwise complement operator.

   <<. This is the signed left shift operator.

   >>. This is the signed right shift operator.

   >>>. This is the unsigned right shift operator.

   &. This is the bitwise AND operator.

   ^. This is the bitwise exclusive OR operator.

   |. This is the bitwise inclusive OR operator.

Java Flow Control Statements

The flow control statements in Java are exactly the same as in C and C++.

   if then statement. The if keyword is followed by an expression and if this expression evaluates to true then the rest of the if statement is executed or the code block is executed such as:

A more concrete example is the following where the code block is executed and prints out an error message to logcat if the m_SoundPool variable is equal to null which means that the sound pool resource failed to be created.

   if then else statement. The if keyword is followed by an expression. If this expression evaluates to true then the code block that follows is executed. However, if the expression evaluates to false then the code block that follows the else keyword is executed such as in:

A more concrete example of an “if then else statement” is where the boolean variable m_AlarmSet is tested and if it is true then the AlarmStatus variable is set to the string “AlarmON.” If the m_AlarmSet variable is false then the AlarmStatus variable is set to “AlarmOFF.”

   switch statement. The switch statement evaluates an expression and tries to match the resulting value with a case block according to the case label such as:


The following is code from an actual Android program. The code is modeled after the standard Android menu callback system. The variable item in the switch statement is a MenuItem object and the case labels represent the menu items that are available to be selected by the user. The exact menu item that has been selected is retrieved by calling item.getItemId(). If the menu item to activate the alarm has been selected then the case block with the R.id.alarm.activate value is executed. If the menu item to deactivate the alarm is selected then the case block with the R.id.alarm_deactivate label is executed. The code in the default code block is executed if none of the other labels matches.

   while statement. The while statement block is executed as long as the expression evaluates to true such as in the following:

A good example of where a while loop is useful is when reading in data over a Wi-Fi connection using the TCP protocol. In the following code while m_IsConnected is true then execute the while loop code block. In the while code block data is read in from a TCP connection and processed by the m_WifiMessageHandler. ReceiveMessage() function.

   for statement. The for statement executes a code block as long as the expression is true. Usually the for loop initializes a variable and then increments the variable at the end of each loop. The value of this variable is used in the for loop block for some processing over a set of objects. The general format for the for loop is:

A good example of using the for loop would be to erase old data from an array. In the following code all the elements in the array m_DataByte are set to 0 starting with the value in array index 0.

   try catch. The try catch block is used for exception handling. The code that is monitored for an exception is located in the try code block. The code to handle any exceptions generated by the code in the try block is located in the catch code block. See the following:

The following is a concrete example of how to use a try catch block in actual Android Java code. The code that is to be monitored for an exception is located in the try code block and creates a new OutputStream file, writes data to it, and then closes it. If there are any problems an exception is thrown and the code in the catch code block is executed. This code write prints the error message so you can view it within the logcat window and displays the error in the program’s graphical user interface.

Java Classes

Java is an object-oriented language like C++ and allows for classes to be derived from other existing classes. The new derived class will inherit the functions and data members of the base class. In this way you can make custom versions of existing classes where you can implement your own functions to customize the behavior of the new derived class. You can tell the compiler to override existing functions in the base class by using the @Override compiler directive. The keyword “extends” is used to indicate that the class that follows is the base class to be extended from. For example, the general format for a Java class DerivedClass that is derived from BaseClass and overrides function1() from the BaseClass is as follows:

A good example of a class in Java that inherits from a base class and overrides existing base class functions is the MainActivity class shown in the code below that inherits from the Activity class. In fact the Activity class is the essential class that you will need to use to develop Android programs. The onCreate() function is overridden and will contain custom code for your specific Android application. The onOptionsItemSelected() function is also overridden and will provide custom code that will process menu items that the user has selected.

public class MainActivity extends Activity

Java Packages

Java Packages are a way to group source code and other files that are part of the same application or perform related functions. The package that a source code file belongs to is usually declared at the start of the file with the keyword “package” such as:

package com.example.gotchacam;

Packages can be imported into a source code file such as:

import java.net.Socket;

The java.net.Socket package that is imported is a standard Android Java package that comes with the Android library and is needed for TCP communication over Wi-Fi. After you import the package you can easily use the classes within the package by just specifying the class name instead of the package name and then the class name. You can also view the packages in your current Android Studio workspace by selecting the Project tab and then select the “Packages” selection from the drop-down menu.

Java Interfaces

A Java interface consists of function declarations but no actual code. The code must be defined by the class that implements the interface. For example, Runnable is a Java interface that is part of the built-in Android library.

public interface Runnable

The only function in the Runnable interface is call run() and is declared as a public abstract function that does not accept any parameters and does not return any value.

public abstract void run ()

A class can implement an interface by using the “implements” keyword in the class definition like in the following:

Here the MainActivity class both inherits from the Activity class and implements the Runnable interface. The run() function is defined later within the MainActivity class.

Java Methods

Java methods are like C and C++ functions. They both refer to the same thing. A Java method is defined by a name and an optional list of parameters, an optional return type, and optional data modifiers such as public, private, etc. If a parameter is an object then it is automatically passed by reference. A basic outline of a method’s structure is as follows:

The following method is called SetCommand and takes a String object as an input parameter and does not return any value.

The following method is named GetStringData and does not take any input parameters and returns a String object.

The following method is named GetBinaryData that does not take input parameters and returns a pointer to an array of type byte.

Accessing Methods, and Class members in Java

In Java you can access methods, and class members just like in C++ with a dot or “.” operator. For example, the m_ClientConnectThread variable is declared to be a class of type Client and initialized to null.

Client m_ClientConnectThread=null;

A new Client object is created and m_Client ConnectThread is set to refer to this new Client object.

If the thread is not null and thus was created then start the thread by calling the m_Client ConnectThread.start() function.

Calling the Parent Method in Java

A Java method that overrides a method that is declared in a base class can call the base class’s method by using the super.BaseMethod() calling format. For example, the class MainActivity is derived from the base class of Activity which has the following method:

The MainActivity class overrides the onCreate method and is required to call the base class’s implementation of this function. In fact the official Android documentation states that for this function:

“Derived classes must call through to the super class’s implementation of this method. If they do not, an exception will be thrown. If you override this method you must call through to the superclass implementation.”

The call to the superclass implementation of the onCreate function is the following:

super.onCreate(savedInstanceState);

The following code shows everything in context:

The Android Activity Class

The one class that is essential for an Android application and that will run on all Android versions is the Activity class which represents the actual Android program or activity. The Activity class is a public class that derives from the ContextThemeWrapper class and implements the interfaces of LayoutInflater.Factory2, Window.Callback, KeyEvent.Callback, View.OnCreateContextMenuListener, and ComponentCallbacks2. See the following:

Generally, the way you will use the Activity class is to define your own custom class that derives from the Activity class such as:

The MainActivity class will hold your custom code that will define the custom behavior for your application. Custom behavior can involve the graphical user interface, storage-related operations, as well as other custom initialization operations.

The following statement imports the Activity class into your source code file so that it can be easily used:

import android.app.Activity;

The official documentation on the Activity class is located at https://developer.android.com/reference/android/app/Activity.

The Android Activity Life Cycle

The Android Activity class calls certain functions during its life cycle from the application being created to the application being put into the background and then when the application is terminated.

The key functions that are called during various stages of the Activity class’s life cycle are the following:

   onCreate()

   onStart()

   onRestart()

   onStop()

   onResume()

   onPause()

   onDestroy()

The MainActivity class uses these functions and is shown in Listing 3-1.

A flowchart of how and under what conditions these key life-cycle functions are called under is shown in Figure 3-13.

Figure 3-13   The Android Activity life cycle.

Android Phone Orientation Change Issue

An important thing to note for developers new to Android development is that by default an orientation change in the graphical user interface causes the application to restart and lose any current data. The way to get around this is to the Activity class’s setRequestedOrientation() function to fix the orientation of the application’s graphical user interface so that it does not change when the phone’s orientation changes. This function is defined as follows:

The following are all the screen orientation options:

   SCREEN_ORIENTATION_UNSPECIFIED

   SCREEN_ORIENTATION_LANDSCAPE

   SCREEN_ORIENTATION_PORTRAIT

   SCREEN_ORIENTATION_USER

   SCREEN_ORIENTATION_BEHIND SCREEN_ORIENTATION_SENSOR

   SCREEN_ORIENTATION_NOSENSOR

   SCREEN_ORIENTATION_SENSOR_LANDSCAPE

   SCREEN_ORIENTATION_SENSOR_PORTRAIT

   SCREEN_ORIENTATION_REVERSE_LANDSCAPE

   SCREEN_ORIENTATION_REVERSE_PORTRAIT

   SCREEN_ORIENTATION_FULL_SENSOR

   SCREEN_ORIENTATION_USER_LANDSCAPE

   SCREEN_ORIENTATION_USER_PORTRAIT

   SCREEN_ORIENTATION_FULL_USER

   SCREEN_ORIENTATION_LOCKED

For example, put the following line of code near the beginning of the onCreate() function to set the screen orientation to the portrait mode.

Hands-on Example: The Hello World Example

In this hands-on example we will be creating a new Android project from scratch, modifying the code and the graphical user interface, and then running it on an actual Android device. First you will need to create the new Android program by selecting the File->New->New Project menu item within Android Studio. This will bring up the new project dialog window. See Figure 3-14.

Figure 3-14   New project dialog window.

There should be options where you can enter an application name, a company domain, a package name, and project location. You can click the “Next” button to move on to the next step. The next screen should be for selecting which platforms your Android program will run on. The “Phone and Tablet” option should already be selected by default. Click on the “Next” button. See Figure 3-15.

Figure 3-15   The target Android devices window.

The next screen should be where you can choose a specific format for your graphical user interface. Select the empty activity graphical user interface and click on the “Next” button. See Figure 3-16.

Figure 3-16   Selecting the Android layout type.

The next screen that is brought up is the “Customize the Activity” screen. Here you can give the activity a unique name. Enter “MainActivityEmpty” in the “Activity Name” field and click on the “Finish” button. See Figure 3-17.

Figure 3-17   The customize activity screen.

The next screen that should pop up will be the project window for the MainActivityEmpty application that you just created. See Figure 3-18.

Figure 3-18   The new MainActivityEmpty project.

Next, you should clean the project by selecting Build->Clean Project from the main menu. Then you should rebuild the project by selecting Build->Rebuild Project. After you are able to rebuild the project without getting any compile errors, attach your Android device to your computer using a USB cable. Make sure you have the developer options enabled on your Android phone. To enable developer options go to the Setting->About Phone section and tap the build number item 9 times to enable the developer options. Go back to the Settings main menu under the “Developer Options” menu and enable USB debugging which sets the debug mode to active whenever the Android device is connected via USB. Select Run->Run ‘app’ to install and run the Android program on your Android device. After you select the Run->Run ‘app’ menu selection the “Device Chooser” window pops up. Select your device from the list and click the “OK” button. See Figure 3-19.

Figure 3-19   Choosing an Android device to run the application on.

After a few moments a new application should start running on the Android device that is attached to your development system via USB cable. The program should have the words “Hello World!” displayed within the graphical user interface. See Figure 3-20.

Figure 3-20   The default Hello World application.

One thing you should notice is that the main activity derives from AppCompatActivity instead of Activity. Let’s change this so that the MainActivityEmpty class will derive from Activity.

The changes you need to make are to:

1.   Comment out the AppCompatActivity class and replace it with the Activity class.

2.   Comment out the import related to the AppCompatActivity class.

3.   Add in the line “import android.app.Activity” in the import section of the code file.

See Figure 3-21.

Figure 3-21   Changing from the AppCompatActivity class to the Activity class.

Run the application with these changes by selecting the Run->Run ‘app’ menu selection. You should see something like the image in Figure 3-22.

Figure 3-22   The Android application derived from the Activity class.

Next, we are going to change the text in the application. In order to do this we need to bring up the layout of the graphical user interface that is located under the res\layout directory. The file is an xml file named “activity_main_activity_empty.xml.” Bring this file up by double clicking on it. It should appear in the source code area. See Figure 3-23.

Figure 3-23   The application’s graphical user interface.

Click on the “Hello World” text in the layout. This should highlight the corresponding text input field in the “Properties” area of the layout where you can enter addition text or change existing text. Enter some new text such as “NEW Hello World with Activity Class!” in the text input field. See Figure 3-24.

Figure 3-24   Changing the default text in the layout.

After you make the text changes run the application again. The new text changes should show up. See Figure 3-25.

Figure 3-25   The Android application with the text changes.

Importing Projects Between Android Studio Versions

New versions of Android Studio are released frequently. Android Studio version 1.5 works on the Windows XP and the most current version of Android Studio is over 3.0. This section will give you some tips on how to convert projects from one version of Android Studio to a more recent version. I tested importing a project from Android Studio version 1.5 to Android Studio version 2.3.1. In order to do this I had to switch the JDK compiler from internal to an external version JDK 8. The reason was that the internal JDK compiler could not be located by Android Studio. See Figure 3-26.

Figure 3-26   Changing the JDK compiler to an external version.

Another issue you may encounter is that the project may require a certain version of gradle. My Android Studio 1.5 project required version 2.2 of gradle which I downloaded from gradle’s official web site at https://gradle.org/.

All versions of gradle are available for download and are located at https://gradle.org/releases/.

After I unzipped the gradle file I set the Android Studio to use the local gradle distribution and checked the option for gradle to work offline. See Figure 3-27.

Figure 3-27   Using the local Gradle version 2.2 and working offline.

Finally, I was able to successfully clean, and rebuild this project for Android Studio 2.3.1. See Figure 3-28.

Figure 3-28   Successful importing of a project from Android Studio 1.5 to Android Studio 2.3.1.

Summary

This chapter gives the reader an introduction into the Android operating system and how to develop programs for this operating system. First some basic information about the Android operating system is presented and then information concerning Android cell phone service is discussed. Next, the system requirements for Android Studio that is used to develop programs for Android devices are covered. I then give an overview of the Android Studio program itself with emphasis on key features that you will need to build and deploy a program to your Android device. Next, I cover the Java programming language that is used to construct Android programs. I cover the basics of Java including data types, program flow control statements, classes, interfaces, and functions. I then cover the Activity class and the Android program’s Activity life cycle. Next, a hands-on example is presented where I show the reader how to use Android Studio to create a new Android application from scratch, modify the program code, change the graphical user interface, and install and run the program on an Android device. Finally, I give an example on how to import an Android Studio project from one version of Android Studio to a newer version of Android Studio.