Contents


Introduction to Android development

The open source appliance platform

Comments

Android is a popular computing platform based on the Linux® operating system. The initial commercial version of Android hit the market in 2008 in the form of a mobile phone platform, back when the most popular cell phone for a business user was the BlackBerry, when the iPhone was beginning to make meaningful waves across all sectors, and when the majority of phone users were still tapping out texts from a flip phone.

Android has "paid its dues," so to speak, in the smartphone market for the past decade. The success of Android and iPhone devices has rendered the one-time business mobile device market leader BlackBerry to be the subject of a Bruce Springsteen song: Glory Days. Interestingly, Android's unprecedented success has helped push BlackBerry into a diverse set of offerings, including shipping devices running the Android platform. (Kudos to the BlackBerry team for pivoting and adding value to their shareholders and the broader market despite experiencing the retreat of their earlier dominance.)

In 10 years' time, Android has effectively become the world's most popular operating system by a number of measures. Despite the robust popularity of the flashy and capable Apple iPhone platform, Android shipments worldwide meaningfully outpace Apple's offerings. While Apple's devices continue to demand an ever-increasing price point, Android devices scale the global marketplace. Yes, there are super-pricy Android models sitting next to the latest iPhone, but there are also relatively low-cost Android phones and tablets available for sale at Walmart and on Amazon.

As Android has matured, it is finding its way into a variety of devices, including televisions, projectors, automobiles, and even recreational vehicles. Want to dim the lights in your camper or activate the awning? You can use the Android-based touchscreen interface to manipulate the controls. Or, use your smartphone equipped with Bluetooth to communicate with the RV's Android-based control system. There are many of these types of interfaces finding their way to the market. Some user experiences are simply fantastic (like drone controllers), and some are less than fantastic, like the controls in my uncle’s RV. This article introduces the Android platform and discusses how you can use it for both mobile and non-mobile applications. The ambition is to get you on a path to making awesome apps for whatever platform arena you feel called to make your contribution.

A brief history of Android

The Android platform was spawned from the efforts of an organization known as the Open Handset Alliance (OHA), which had at the outset the mission of collaborating to "build a better mobile phone." Today, if you visit the Open Handset Alliance website, you might think that their efforts were in vain, as the latest news item dates to 2011. However, what was started with that group of carriers, hardware manufacturers, and software vendors has grown into the world's most popular platform. Is Google the "man behind the curtain" of the OHA? Maybe, but no matter. In the decade since its introduction, Android is offered in the market by many large players across the globe and across numerous industries. Samsung, also a member of the OHA, is the leading manufacturer of smartphone devices worldwide, thanks to Android.

Although a single device (the G1 device manufactured by HTC and provisioned on the T-Mobile network) started it all, Android devices are now available in virtually every market on the planet — not just for mobile phones.

It is beyond the scope of this article, but ask yourself if there is not a correlation between (arguably) the world's most successful Internet/search company also being the driving force behind the world's most popular mobile platform. More eyeballs view Android devices every day worldwide than any other single computing platform.

If you want to write code that can run literally anywhere in the world, then you need to learn about the Android platform, so read on!

The Android platform

Looking at Android's breadth of capabilities, it would be easy to confuse it with a desktop operating system. Android is a layered environment, one that is built upon a foundation of the Linux kernel and includes rich functionality. The user interface subsystem includes everything you would expect from a mature operating system environment including windows, views, and widgets for displaying common elements like edit boxes, lists, or drop-down lists. The browser is both capable for general web browsing and available for embedding directly into your own application.

In the past decade, the mobile web has been transformed by the adoption of smartphones across consumer and business applications, including Android. "Responsive" web technologies have made the utility of mobile devices greatly enhanced.

Figure 1 displays a simplified view of the Android software layers:

  • Applications:
    • Built-in applications, such as phone, contacts, browser, and more. The specific applications vary by Android version and manufacturer.
    • Commercial applications from marketplaces, such as Google Play, Amazon, and more.
    • Side-loaded applications, including the ones you will build. You install these via USB cable.
  • Application frameworks, such as telephony manager, location manager, notification manager, content providers, windowing, resource manager, and more.
  • Libraries, such as graphics libraries, media libraries, database libraries, sensors, and so on.
  • The Android runtime is responsible for executing and managing applications as they run.
  • Linux Kernel, including power, file system, drivers, process management, and more.
Figure 1. Android software layers
The Android software layers
The Android software layers

Android boasts a healthy array of connectivity options including wifi, Bluetooth, NFC, and of course cellular connections on every network that you can imagine. Location-based services power popular mapping and navigation apps. Digital cameras have essentially retreated up-market due to the quality of the cameras found in modern smartphones. Android supports multiple cameras with the ability to capture full motion video. One of my favorite classes of applications is machine vision, where applications use the camera as an input device to perform inspections for manufacturing. Voice-based services make the modern Android device a virtual personal assistant.

If you can dream it, you can program it on the Android platform!

Clearly, Android is a capable computing platform, so let's see what kinds of applications Android can run.

Application architecture

An important aspect of the Android application environment is that Android applications have historically been written in the Java™ programming language. However, you can also write them in a relatively new programming language from Google called Kotlin. This article focuses exclusively on Java, but Kotlin is gaining momentum and you might consider taking a closer look. Between the trend toward "newer is better" in programming languages (for example, Swift is overtaking Objective-C for iOS/Apple development) and the ongoing legal battle over where Java can or cannot be used, Kotlin will likely be the leading language for Android within a few years.

For now, Java is the incumbent technology. If you’re just starting out, Java is a safe place to work for a couple of reasons. First, there is a decade's worth of Android resources on the web focused on Java. Second, Java is a language that still has life in it for other platforms – particularly server-side web technologies. As a classic object-oriented programming language, Java skills still matter.

While it might not matter at this point, there are some interesting details around how Android applications come to life from their underlying source code. Again, in this article, our focus is on Java programming.

Java source code is compiled and formatted into bytecode, which represents the logic of an application but not the specific instructions for a particular hardware device. Similar to traditional Java environments, early versions of Android operated by converting these so-called bytecodes to hardware-specific executable code. This conversion magic is accomplished by using a Just-In-Time (JIT) compiler and takes place each and every time the application is executed. Once the JIT compiler has converted the code, it is executed in a virtual machine known as the Dalvik VM.

Beginning with Android version 4.4 (KitKat), the Dalvik VM has been replaced. The JIT compiler converts bytecodes to executable code directly on the device at runtime each time the application runs; the new approach is called Ahead-of-Time (AOT) compilation. With AOT compilation, the byte code is converted only once when the application is installed. This slows down the one-time activity of installing the application but gains the benefit of faster execution at run time when it really matters.

With AOT, we enjoy faster runtime experience with lower RAM requirements at the expense of more storage requirements. Considering the incessant decline in the cost of storage, this is an agreeable direction to move in for our mobile applications. Figure 2 contrasts the old and the new execution environments.

Figure 2. Dalvik VM versus Android runtime
Dalvik VM
Dalvik VM

Fundamentals of Android development

Regardless of the moving pieces of how applications get converted from source code to running code, from a programming perspective, there are some fundamentals to understand when starting out with Android development.

An Android application consists of one or more of the following four classifications:

  • Activities: An application that has a visible user interface is implemented via an activity. When you select an application from the Home screen or application launcher, an activity is started.
  • Services: You can use a service for any application that needs to persist for a long time, such as a network monitor or update-checking application.
  • Content providers: The easiest way to think about content providers is to view them as a database server. A content provider's job is to manage access to persisted data, such as the contacts on a phone. If your application is very simple, you might not necessarily create a content provider, however if you are building a larger application or one which makes data available to multiple activities and/or applications, a content provider is the proscribed means of accessing your data.
  • Broadcast receivers: You can launch an Android application to process a specific element of data or respond to an event, such as receiving a text message.

An Android application is deployed to a device along with a file named AndroidManifest.xml. This file is required for every Android application and is essentially the cheat sheet that tells the operating system exactly how to interact with your application. The AndroidManifest.xml includes both the required class names and types of events that the application is able to process as well as the required permissions that the application needs to run. For example, if an application requires access to the network to download a file, this permission must be explicitly stated in the manifest file. Or, perhaps an application needs to access the camera. The user needs to approve that also. This approach of declaratively telling the user what the application is going to use is essential in this day of increasing privacy and security concerns. While you can quickly just accept software licenses, it is important that you pay close attention to what an app is requesting to access.

Enough background…let’s have a look at the development environment required to build an Android application.

Exploring Android Studio

The easiest way to get started with developing Android applications is to download the Android Studio application suite. You can download a copy of Android Studio for your preferred platform (Windows®, Mac OS X, or Linux) from the Android developers site. Android Studio includes tools for managing multiple platform-specific features with the sdkmanager and the ability to test your application on either a real device or the emulator.

There are older generations of development tools, including Android Developer Tools (ADT), which is the predecessor to Android Studio, and Eclipse with an Android Developer Tools plug-in, which was the predecessor to ADT. In essence, Android Studio is the third generation of the Android Integrated Developer Environment (IDE). There are also command-line tools and various continuous integration toolchains that permit the building of Android applications.

This article assumes that you are using Android Studio. Coding in Java within Android Studio is intuitive because it provides a rich Java environment, including context-sensitive help and code suggestion hints. After you compile your Java code cleanly, the components of Android Studio make sure all of the application is packaged properly, including the AndroidManifest.xml file.

Let's take a quick look at the contents of the SDK.

The sdkmanager, which ships as an integrated experience of Android Studio, manages the download of the numerous elements of the Android SDK. Figure 3 shows a subset of the SDK installed on a Mac.

Figure 3. Android SDK
The Android Emulator
The Android Emulator

Note that a common experience with Android development is that you might wind up with multiple versions of the SDK installed because you will likely target multiple versions of Android devices with your application. The sdkmanager assists you in making a choice regarding which SDKs to select. The Android tools that are available are a bit overwhelming if you dig deep enough. However, as a beginner, don't worry about all the details until you find that you need a specific version. After a couple of dives into the process, it will become familiar to you.

You can run Android applications on a real device or on the Android Emulator, which ships along with the Android SDK. Figure 4 shows the Android Emulator’s home screen.

Figure 4. Android Emulator
Using the adb shell command
Using the adb shell command

Next, let's take a little closer look at the adb utility, which is the Android Debug Bridge. adb supports many optional command line arguments that provide powerful features, such as copying files to and from the device. With the shell command-line argument, you can connect to the phone itself and issue rudimentary shell commands. Figure 5 demonstrates the use of the adb shell command against a real device connected to a Windows laptop via a USB cable.

Figure 5. Running adb shell against a Samsung device
Running adb shell against a Samsung device
Running adb shell against a Samsung device

Referring to Figure 5, we see a few of the things we were able to accomplish within this shell environment:

  • Display the network configuration, which shows multiple network connections. Note the multiple network connections:
    • lo is the local or loopback connection
    • wlan0 is the wifi connection with an address provisioned via a local DHCP server
  • List the contents of the sdcard.
  • Display the contents of the PATH environment variable.
  • Issue a ping command to see if google.com is available.

From this same command prompt environment, we can also interact with SQLite databases, start programs, and perform many other system-level tasks. This is some pretty remarkable functionality considering we are connected to a telephone! Note that some features require access to either a rooted phone or a developer phone. A developer phone is a device that is available for purchase for the express purpose of gaining more access to the device to aid in developing applications.

Now that you have a little better understanding of the development tools and the environment that is available to you, let’s take a brief look at creating a simple Android application.

Coding a basic application

We are going to take a whirlwind tour of building an Android application. This application is about as simple an application as can be imagined: just a "Hello Android" application.

To create the application, we will follow the new application wizard to step us through the process in a pretty painless manner.

We will call our application Flashlight, in honor of my first application written for Android over 10 years ago.

Figure 6. Creating a new application
Creating a new application
Creating a new application

For now, we’re sticking with Java, so we leave the C++ and Kotlin options clear.

Figure 7. Targeting Android devices
Targeting Android devices
Targeting Android devices

We have to decide which platforms and SDK levels to support. Notice the options available: Phone and Tablet, Wearables, TV, Auto, and Things(!).

Figure 8. Making an intentional choice of devices to target
Making an intentional choice of devices to target
Making an intentional choice of devices to target

After selecting Phone and Tablet, we need to select which SDK revision level we want to target. We are choosing to roll back the SDK level from Android "P," which at the time of this writing was supported on less than 1 percent of shipped devices, and instead choose Android version 4.1 (Jelly Bean), which is supported by nearly 100 percent of Android devices.

Quick note: Android devices have generally been extremely accommodating with respect to being compatible with earlier versions. This is tightening up a bit, but Android is much friendlier than Apple iOS in this regard. You can make an argument that Apple has good reasons for pushing users to upgrade, with security concerns being one significant reason. This might not seem too big a deal right now; however, as an app developer, you will quickly feel the stress associated with the requirement of constantly updating your app for the latest version. With Android, you have a little more breathing room.

Figure 9. Jump-start the application by adding an activity
Jump start the application by adding an activity
Jump start the application by adding an activity

This step creates a simple application with a single activity along with a single user interface layout. The layout contains a single text element, which we are going to modify to say, "Android FlashLight." Listing 1 shows our simplistic layout.

Listing 1. Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    tools:context=".MainActivity">
    <include layout="@layout/content_main" />
</android.support.design.widget.CoordinatorLayout>

The file activity_main.xml defines the user interface for this single activity application. Note that there is an "include" tag that pulls in the file content_main layout, shown in Listing 2.

Listing 2. Content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:background="@color/colorOrange"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Flashlight"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Note the attribute named android:Background: it is set to colorOrange, which we have defined in the colors.xml file, shown in Listing 3.

Listing 3. Colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>

    <color name="colorPrimaryDark">#303F9F</color>

    <color name="colorAccent">#FF4081</color>

    <color name="colorWhite">#FFFFFF</color>

    <color name="colorBlack">#000000</color>

    <color name="colorOrange">#FFA500</color>

</resources>

The layout contains a single TextView — which is just a piece of static text — that is not editable. The constraint attributes serve to center the text.

The application has a java source file named MainActivity.java, shown in Listing 4.

Listing 4. MainActivity.java
package com.navitend.flashlight;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

Listing 4 is boilerplate directly from the New Project wizard. A few things to note about this code:

  • It is part of a Java package, named com.navitend.flashlight.
  • It has two imports: one for the Activity class and one for the Bundle class.
  • When this Activity is initiated, the onCreate method is invoked, passing in a savedInstanceState. We are not concerned with this Bundle for our purposes; it is used when an Activity is suspended and then resumed.
  • The onCreate method is an override of the Activity class method of the same name.
    • We call the super class’s onCreate method.
  • A call to setContentView() associates the user interface layout defined in the file main.xml.
    • Anything in activity_main.xml and colors.xml gets automatically mapped to constants defined in the R.java source file. Never edit this file directly as it is changed upon every build.

Running the application presents an orange screen with black text, as seen in Figure 10.

Figure 10. Our Android Flashlight application running
Our Android Flashlight application running
Our Android Flashlight application running

To bring some closure to what we discussed earlier about the AndroidManifest.xml file, have a look at the AndroidManifest.xml file setup for our FlashLight application, shown in Listing 5:

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

    <application
        android:allowBackup="true"
        android:installLocation="preferExternal"
        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>

Note that this file was created automatically by Android Studio — we didn’t have to do anything!

Of course, this is not the most magnificent of applications, but it is a safe and simple first application. If you can build this application and get it to run, you’re on your way to bigger and better things!

Conclusion

This article served as an introduction to Android from a high level, including just enough hands-on coding to hopefully get you excited to explore more of the Android platform. Android has gone from market entrant to dominant force in its relatively brief existence. Upcoming articles dig deeper as we explore the capabilities of this remarkable platform.


Downloadable resources


Related topics


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Industries
ArticleID=387678
ArticleTitle=Introduction to Android development
publish-date=05302018