Mobile for the masses: A gentle introduction to Android

Survey Android's mobile landscape and build your first app!

The mobile landscape is rich with promise, and Android is a viable and exciting platform for developers who seek a way in. This new series starts with an introduction to Android that is tailored specifically for Java™ developers just getting started with mobile. Learn about Android's three-layer versioning system (and find out why it matters), then set up your development environment and build your first Android app.

Andrew Glover, CTO, App47

Andrew GloverAndrew Glover is a developer and mobile technology enthusiast. He's currently the CTO of App47 and is the founder of the easyb behavior-driven development (BDD) framework. He is also the co-author of three books: Continuous Integration, Groovy in Action, and Java Testing Patterns. You can keep up with Andrew by reading his blog and by following him on Twitter.



05 March 2013

Also available in Chinese Russian Japanese Vietnamese

Introduction

About this series

Mobile application distribution is exploding, and so is the market for mobile development skills. This developerWorks series introduces the mobile landscape to developers who are experienced with programming but new to mobility.

Start out coding native apps in Java™ code, then expand your toolkit to include JVM languages, scripting frameworks, HTML5/CSS/JavaScript, third-party tools, and more. Step by step, you'll master the skills you need to meet virtually any mobile development scenario.

The recent surge in mobile technology usage is astounding even to industry insiders. Apple CEO Tim Cook summed up the feeling in a September 2012 interview, as he discussed Apple's success with the iPad. Selling 67 million iPads in two short years is remarkable under any circumstances. Cook put that number into historical perspective when he noted that "it took us 24 years to sell that many Macs and five years for that many iPods and over three years for that many iPhones." (See Resources.)

If iOS is doing well, then Android, the Java-centric platform, is also keeping pace. According to a recent statement by Google, 500 million Android devices were activated since Android was officially released in 2008, and 1.3 million new devices are activated daily. Altogether, Apple's iTunes App Store and Google Play reportedly list at least 1,400,000 apps and more than 60,000,000,000 mobile application downloads. (See Resources.)

All these mobile device activations mean new opportunities for application sales and a growing market for mobile development skills. For developers who want to build mobile skills fast, Android is an excellent place to start. If you can write in Java code and other JVM languages, you can focus your initial learning curve on the requirements of mobile deployment and build from there. Android's versatility means that you can easily adopt and experiment with newer technologies like HTML5 and PhoneGap. And its platform ubiquity—along with Google Play—ensures that your production apps can be widely distributable.

This first article in the new Mobile for the masses series is a gentle introduction to Android. You start with an overview of Android's rather elaborate versioning system, then set up a development environment and start to build your first app.

Three ways to go mobile

At a high level, the mobile ecosystem has three primary development platforms: native, web, and hybrid.

  • Native platforms yield apps with a superior look, feel, and performance when compared to other options. The downside of building native apps is that you must write a different code base for every platform.
  • Web mobile apps are typically written in HTML5, CSS, and JavaScript. You can write a web mobile app once and run it on multiple platforms, but it might not have the polished look, feel, and performance of a native app.
  • Hybrid tools and frameworks bridge the gap as they combine the easy coding and ubiquity of web apps with the sheen of a native app. Developers argue a lot about which platform is better (some call it "The great mobile app debate") but the truth is that each has its advantages.

This series covers all three platforms.


Wild about Android

Android device distribution is growing faster than any other mobile platform, which makes it an excellent choice for your first mobile development journey, especially if you are a Java developer. A downside of Android's massive adoption is fragmentation, which presents significant challenges for testing applications. The reality for most developers is that it is almost impossible to test an app for every combination of Android device-to-OS version profile. (In fact, doing so in a cost-effective manner is a growing service industry.) Later articles look at technical issues that involve porting to multiple Android profiles, plus Java-based tools for testing Android mobile apps. For now, survey Android's versioning landscape so you can understand it to develop for this platform.

Android versioning

While the version numbers of Android OS releases are sequential—1.6, 2.1, 4.2, and so forth. Releases are also named after various items in a scrumptious dessert menu: Donut, Eclair, and Jelly Bean. When someone refers to Jelly Bean in the context of Android, they mean Android version 4.2. Android versions are also delineated at the API level, by sequential ascending integers. So Android API level 17 refers to Android version 4.2, which is also known as Jelly Bean.

If you think that is unclear, you are not alone. Still, an understanding is important because the three versioning schemes are used interchangeably.

Most Java developers must reverse their basic mindset when it comes to supporting different Android versions. The Java platform rose to fame primarily as a server-side technology, where the touch point for a user was usually a web page. If the web page is viewable, readers of a web page do not care which Java version your app runs on. With Android, however, your application code leaves the safety of your servers and runs on devices where you have no control.

Many potential consumers of your app upgrade to a newer version of the Android OS only when their old device dies. Your decision of which Android operating system to support is crucial. While the most current version of Android is 4.2, roughly half of Android devices still support Android 2.3.x. An app that is written to target Android 3.1 does run on newer versions such as 4.2, but does not run on earlier versions like 2.3. So, it stands to reason, if you want a wider distribution, your better choice is to target an older version of the operating system.

A downside of targeting the older, more widely distributed platform is that newer versions always have new features, some of which you want for your app. If you are lucky, the Android development team will release compatibility libraries so you can use the newer features on an older version.


Up and running with Android and Eclipse ADT

As the first part of this gentle introduction to Android, I help you creat a simple Android app as quickly as possible. You'll use Android 4.2 and the Eclipse Android Development Tools (ADT) plugin to produce everyone's favorite: A Java-based Hello World app.

Android-compatible IDEs

When you develop mobile applications for Android, you use Java tools and frameworks that are probably familiar. For instance, the two most popular IDEs for Java development, Eclipse and IntelliJ, both support Android. Android has tight bindings into Eclipse, with plugins that make the build-test-deploy cycle for Android apps nearly effortless. The examples in the article are built with Eclipse, but work as well if you use IntelliJ.

Choose from two paths to set up your development environment for Android. Developers new to both Eclipse and Android can start by downloading the ADT (Android Developer Tools) Bundle. The ADT Bundle combines the Android SDK and a version of Eclipse that has the ADT plugin that is already installed. The bundle is a quick, easy way to start with Android.

If Eclipse is installed and set up on your desktop already, then manually download and install the Android SDK. The base Android SDK contains system-level tools that facilitate developing with Android. However, it lacks the actual Android libraries that are required to develop for a particular version of Android. After you download the base Android SDK for your operating system, go into the tools directory of the SDK installation and run the Android script in Listing 1.

Listing 1. Start the Android SDK Manager
~/Development/tools/android/android-sdk-mac_x86/tools$>./android

This script fires up the Android SDK Manager, ready for you to download various versions and libraries for Android and create emulator or virtual device instances. The Android SDK Manager opens to a window with a large list of options to download, as in Figure 1.

Figure 1. The SDK Manager
A screenshot of the SDK Manager

In the check boxes on the left, select Tools and then select Android 4.2 (API 17). That folder displays a number of options. Select the SDK Platform and the ARM EABI v7a System image, as in Figure 2.

Figure 2. Selections in the SDK Manager
Screen capture of system and tools options in the SDK Manager

Click Install packages and accept any license that is required; the manager does the rest.

Creating an emulator

Next, create an emulator instance, which is a virtual device on which you can run apps. Emulators must target a particular version of Android, so create an emulator instance that runs Android 4.2.

Start your SDK Manager again if you closed it. If the Android SDK tools or platform tools were updated, restart the SDK Manager. In the top-level menu of the SDK Manager, select Tools > Manage AVDs to open a new dialog for the Android Virtual Device Manager, as in Figure 3.

Figure 3. Android Virtual Device Manager
Screen capture of selecting the Android Virtual Device Manager from the Tools menu

This dialog lists any emulators that are defined on your machine. The emulator list is empty until you create one. Click New to open the Create a new Android Virtual Device (AVD) dialog in which you can define an emulator. In the Target drop-down list, select Android version 4.2. In the AVD Name field, give your emulator a name—mine is Android_4.2. When you are ready to test your app, use this name to start the emulator from the command line.

Figure 4. Creating a new Android virtual Device
Screen capture of creating a new Android virtual device in the SDK Manager

In Figure 4, you have a few options for AVDs, including the device type, camera settings, memory, and storage. In my case, I picked a Galaxy Nexus, giving it an SD card with 200 MB. Finally, I checked the Use Host GPU emulation option, which can improve the performance of emulator instances.

Click OK to see your new virtual device that is listed in the AVD dialog. Select it and click Start to open another dialog with launch options. For now, keep the defaults and click Launch. An emulator instance can take some time to start, so get some coffee, check Facebook, or update your Twitter status.

Figure 5. A new Android device!
Screen capture of the AVD rendering for Galaxy Nexus

After a few moments, a shiny simulated device (similar to Figure 5) displays on your home screen, which means that you are good to go! You are ready to start building Android 4.2 apps.

Setting up Eclipse ADT

If Eclipse is installed on your system then, you must add the Android Development Tools (ADT) plugin repository before you continue.

In the Eclipse menu, open Help > Find New Software. Click Add and the URL for the ADT plugin: https://dl-ssl.google.com/android/eclipse/ (see Figure 6).

Figure 6. Adding the ADT plugin repository
Screen capture showing options to add the ADT plugin repository for Eclipse

After the plugin downloads, follow the instructions to install it. Configure the ADT plugin to use the SDK that you already installed. Now your project targets the Android 4.2 platform and uses your configured emulator.


Hello, Android 4.2!

To create an Android app in Eclipse, select the option to create an Android Application Project. In the New Android Application dialog, provide an application name, project name, and package name. The application name is what users see under your device icon; the project name is the name of your project in Eclipse.

Figure 7. Creating a new Android project
Screen capture of creating a new Android project

Start from the New Android Application dialog in Figure 7 and take these steps:

  1. In the Target SDK drop-down list, select API 17: Android 4.2 (Jelly Bean), then click Next.
  2. In the next dialog, keep the default settings, although you can place the resulting code in any location. Click Next.
  3. Keep the defaults in the Configure Launcher Icon dialog and click Next.
  4. Also, keep the defaults in the Create Activity dialog and in the final dialog, which is used to select your application's activity. Click Finish.

If your project creation worked, you now see a new project with a simple user interface similar to Figure 8.

Figure 8. A sample startup project in Eclipse
Screen capture of a default application in Eclipse

Run your app in the Android emulator

By default, Android projects that are created with the ADT project wizard create a simple Hello World mobile app! (See Figure 8.) Before you start to embellish it, see what happens when you run the basic app in an emulator.

If you closed it down, open your Android 4.2 emulator. Rather than start the emulator in the AVD Manager, this time try it through the command line. You can access the emulator script from the SDK's tools directory. When you start the script, provide the name of your emulator. My emulator was named Android_4.2, so I run the script in Listing 2 to start my emulator instance:

Listing 2. Accessing the emulator on the command-line
~/Development/tools/android/android-sdk-mac_x86/tools$>./emulator -avd Android_4.2

Start your emulator instance, return to Eclipse, and select your project. Right-click, and select Run As > Android Application.

Figure 9. Running your project from within Eclipse
Screen capture of the app running in Eclipse

By default, Eclipse deploys your app on the currently running emulator (Figure 9). Your emulator instance now shows a large white screen that bears every Java developer's favorite greeting! If for any reason Eclipse has trouble when it runs your app on the emulator, return to the Run As option and select Run Configurations. On the Target tab, recheck Automatically select compatible device and ensure that your emulator is selected.

Figure 10. Hello World!
Screen capture of the 'Hello World' app

A basic Android app

You now have a basic Hello World application that runs in any 4.2-compatible Android device. Eventually, you want to customize that app and add more interesting functions. For now, I want to go over the anatomy of an Android application.

Android's specialized JVM

Android apps are written in Java code but they do not run on a standard JVM. As part of an Android build, the Java byte code is transformed and specialized for the memory and processing requirements of a mobile device. See Resources to learn more about the architecture of an Android application and the Dalvik virtual machine.

Go back to your Eclipse IDE. In the src directory of your project, navigate to the single .java file in your project. If you kept all the defaults, this file is named MainActivity. Activity classes are the workhorses of an Android mobile app, similar to servlets for Java server-side apps. Every Activity has a lifecycle, which is akin to the lifecycle of a Java applet (if you remember them from back in the day).

The Hello World app is basic, so its Activity is simple. First, the class extends from Android's Activity class. The entry point for activities is through the onCreate method, which is started by the platform when your app is loaded. The key line in that method is the setContentView invocation. Listing 3 shows the default MainActivity class.

Listing 3. MainActivity
package com.example.hello;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

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

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
}

In Listing 3, the setContentView loads the activity_main layout, which was the name of the view that you saw in Eclipse when you first opened your project. This name corresponds with the activity_main.xml file that lives in the res/layout directory. Open this file to see a graphical view of your app. In the lower-left tab of the view is an option to view the raw XML file. Click that option to see the raw file, which looks like Listing 4.

Listing 4. A raw layout definition
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />
</RelativeLayout>

Android views are defined in XML files. Each view has a layout to which you can add widgets such as buttons or text fields. For now, the sample app has a RelativeLayout with one widget: a TextView. If you look closely at that widget, you see a text field that is set to a reference: @string/hello_world.

That variable is a pointer to a real string value, which you can find in the res/values/strings.xml file. Open that file. To view the raw XML, click the strings.xml tab in the lower-left area.

Listing 5. The strings.xml file
<?xml version="1.0" encoding="utf-8"?>
<resources>
 <string name="app_name">Hello 4.2</string>
 <string name="hello_world">Hello world!</string>
 <string name="menu_settings">Settings</string>
</resources>

The second string definition from Listing 5 maps hello_world to Hello World!.

The Android manifest

You've seen thus far how three important elements of an Android app are connected: activities, layouts, and resource files. When your app starts, the Android OS calls the onCreate method of your MainActivity. The onCreate method then loads a layout, and that layout grabs some values from another XML resource file. In this case, the result is a simple UI that says "Hello World!"

But how does a device know which Activity to call? Now the AndroidManifest.xml comes into play. Look for this file in the root directory of your project. Click it and Eclipse loads a nifty custom view with a few tabs in the lower-left corner of the view. Click the tab that is labeled AndroidManifest.xml to display the raw XML in Listing 6.

Listing 6. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.hello"
   android:versionCode="1"
   android:versionName="1.0" >

  <uses-sdk
   android:minSdkVersion="8"
   android:targetSdkVersion="17" />

  <application
   android:allowBackup="true"
   android:icon="@drawable/ic_launcher"
   android:label="@string/app_name"
   android:theme="@style/AppTheme" >
   <activity
    android:name="com.example.hello.MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
     <action android:name="android.intent.action.MAIN" />
     <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter> 
   </activity>
  </application>
</manifest>

The purpose of this file is to explain your app to an underlying device. It includes an XML block that is called application, which defines the activity. Your MainActivity is referenced and an action is defined along with a category. The action tells a device which Activity to start. In this case, the action delineates your Activity as MAIN.

Other important declarations in the AndroidManifest.xml file include the uses-sdk portion, which says that the min version is 8 (that is, Android 2.2.x) and the target is 17, also known as Android 4.2. I cover these details in a later article. For now, suffice it to say that the Android platform provides libraries that are compatible with earlier versions.


In conclusion

Your first Android app is off to a good start. In the process, you learned some important things about Android—and mobile development generally. You installed Android's SDK, downloaded Android version 4.2, and created an AVD (or emulator) to simulate the running of your app on a device. If you use Eclipse, your IDE is now configured to build and deploy Android apps to your AVD of choice. All of this setup is required to get anything done with Android.

You also saw how a simple Android app is wired together, with Activity classes to do most of the work while the AndroidManifest.xml defines it for the underlying device. And you saw the results: a simple Hello World app, just waiting to be customized.

We'll go further with Android next time. In the meantime, I encourage you to play with the app setup that you have so far. Add some widgets or change the values of aspects in your XML files. If you feel more ambitious, try to create a new Hello World app, but without the defaults.

Resources

Learn

Get products and technologies

  • Download Android: The Android SDK provides you the API libraries and developer tools necessary to build, test, and debug apps for Android.
  • ADT (Android Developer Tools) Bundle: Download the Android SDK and a version of Eclipse with the ADT plugin already installed for a quick and easy start with Android.
  • Download IBM developer kits: Update your system and get the latest tools and technologies here.

Discuss

  • The developerWorks community: Connect with other developerWorks users as you explore the developer-driven blogs, forums, groups, and wikis.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Java technology on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology, Mobile development, Open source
ArticleID=860218
ArticleTitle=Mobile for the masses: A gentle introduction to Android
publish-date=03052013