Skip navigation
green android sprite with text below Im so cool

Get Started Building Android Apps

Learn the essentials of Android app development

Android has been steadily gaining momentum as a mobile application platform and is now prevalent enough that developers ought to learn at least the basics of developing Android apps. For developers new to Android, the good news is that learning to develop for Android is far easier than learning to develop for iOS, at least without the help of higher-level tools such as Xamarin Studio. To start writing truly native Android apps, you will need to learn the Java language and obtain an IDE for your preferred OS platform (Windows, Mac, or Linux). Google's Android Studio or JetBrains' IntelliJ IDEA (upon which Android Studio is built) are two excellent and free Android IDE options. Alternatively, Eclipse remains a viable option for Android application development.

In this article, I'll discuss what it takes to create a sample Android application that provides minimal user interactivity. In doing so, I'll touch on aspects such as the lifecycle of an Android app and navigation. However, I will not cover more specific topics such as networking, local storage, and data binding. At the end of the day, though, Android development is easy to learn because once you've mastered the basics, everything else is as simple as learning a new set of classes.

Getting Ready to Build an Android App

Both IntelliJ IDEA and Android Studio come with a nice installer that sets up most, but not all, the necessary Android components. After the setup program is completed, you still need to perform a few steps yourself. In particular, you should list the versions of the Android operating system you intend to support in the IDE. For each selected version, you then need to download specific binaries and, optionally, examples. To perform these tasks, you use the Android SDK Manager tool, which is integrated into the user interface in both Android Studio and IntelliJ IDEA, as shown in Figure 1. Through the SDK Manager, you select the version of the Android platform you intend to build for, and the tool downloads and installs binaries, additional tools, and optionally, samples.

Figure 1: Android SDK Manager
Figure 1: Android SDK Manager

At this point, you're ready to start building your first Android application. The project wizard is nearly the same regardless of the IDE you use, whether it's Android Studio, IntelliJ IDEA, or Eclipse. For the purposes of this article, I'll be using IntelliJ IDEA Community Edition. It is worth noting, though, that Android Studio is built from the same codebase as IntelliJ IDEA Community Edition.

Straight out of the project wizard, the first Android application is fairly simple: a manifest file, one activity class, and one basic graphic layout. This is a fully functional application in the sense that it compiles well and can be installed on devices. However, it doesn't yet support any form of interaction.

Making Sense of Activities

An Android application is built around one or more screens. Each screen requires its own activity class. The activity class is expected to contain any code behind the screen—specifically code that initializes the view and handles events. Let's have a look at the activity class for the app's main screen. The class is named MyActivity and lives in the src folder. Any Android activity class inherits from the system-defined Activity class, as shown in the following example:

public class MyActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
    }
}

At the very minimum, an activity class overrides the onCreate method defined on the base class. In the override, you first call the base method, then set the content view. In the previous code snippet, the expression R.layout.main references the project file where the layout of the view is saved.

You can think of the activity class as the equivalent of the code-behind class of a .NET Framework application. There you will handle references to UI elements and set event handlers. To define the graphical layout, you use a WYSIWYG editor integrated in the IDE (IntelliJ IDEA, Android Studio, or Eclipse). The graphical editor works as expected and lets you pick visual widgets from a palette and drop them on a drawing surface. Figure 2 shows the application's UI that I created with the graphical editor.

Figure 2: The Sample Android App's UI
Figure 2: The Sample Android App's UI

The graphical editor produces an XML file that can also be edited manually through an ad hoc text editor in the IDE. Overall, the Android XML layout language is in some ways similar to XAML and, as with XAML in Visual Studio, you can create and edit the XML file using either a visual or a text editor. You compose the UI hierarchy through panel components such as the LinearLayout or RelativeLayout elements, which map closely to StackPanel elements in XAML. Listing 1 shows the XML code for the graphical layout shown in Figure 2.



    
    
    
    

Each Android UI widget is required to indicate explicitly its width and height. However, you often use relative measurements for this. For example, wrap_content indicates that the size of the component is enough to incorporate any content. Likewise, fill_parent indicates that width or height needs to be as big as the container component. If you intend to use fixed measures, you should use either the dp or dip qualifier to mark those values as device-independent pixels. You should avoid using any other measure qualifier, as dp (or dip) ensures the best scaling experience for the UI on smaller or larger devices.

Finally, you should note the special syntax required to assign an ID to a visual element or to bind a resource. The at sign (@) indicates a reference. Thus @string/messageDontTouch refers to a string resource named messageDontTouch.

Resources are stored in special XML files under the res project folder. Basically, Android compiles resources into a dynamically created class—this happens in a way that's analogous to how .resx files are processed in .NET code. The name of this dynamically created class is R, and it exposes properties for nearly any type of resource in the project. For IDs, there's an extra plus sign (+) to take into account. The + sign associated with ID resources exists to explicitly indicate that the resource must be added to the list. This is to distinguish between Android native IDs and user-defined IDs.

Finding References to Visual Elements

In .NET, any element defined from within the graphical layout can be consumed from code via an object reference. In .NET, however, UI object references are automatically managed by Visual Studio and the C# compiler through the mechanism of partial classes. In Android, you are responsible for defining object references yourself. To do so, you first add a private member to the class for each graphical component to reference:

private TextView message;
private ImageView droid;

Next, directly in the code of onCreate or, better yet, in a distinct method, you initialize the private members:

message = (TextView) findViewById(R.id.message);
droid = (ImageView) findViewById(R.id.imageView);

The type cast is necessary because findViewById—a method defined on the base Activity class—always returns a generic View object. This part of Android programming is quite boring but necessary, and, at least for the time being, there's no other way to accomplish it.

Adding Event Handlers

To add a handler to events fired by visual component, you follow the same pattern as in C#, except that the Java syntax is more boring. You first define an explicit handler:

private View.OnClickListener droidTapListener;

Next, you bind the event handler to some code that will run in response to the event:

droidTapListener = new View.OnClickListener() {
    public void onClick(View v) {
     touchDroid();
    }
};
droid.setOnClickListener(droidTapListener);

In this example, touchDroid is just an internal method that actually performs the task. Note the verbosity of the Java syntax. In C# you would have simply bound touchDroid to the event. In Android, you also need to explicitly make the event assignment using an event-specific method. For the click event, the method is setOnClickListener. In the touchDroid method, you perform any task associated with the event and then use references to visual elements to update the UI.

The Manifest File

The manifest file is mandatory for any Android application and is created for you along with the project. The manifest file contains information that the app presents to the operating system when the app is installed on the device. This information includes the app's package name and icon and the name of the starter activity. Optionally, the manifest can contain requested permissions that the user should grant to the application so that the app can run. These permissions typically include the permission to access items such as contacts, network, phone state, local storage, vibration, and others.

Declaring all necessary permissions is crucial, as the application won't work otherwise. The Android API, in fact, implements a security layer that prevents the API call from working if it requires permission and the app doesn't declare that permission in the manifest file. The manifest file is saved as an XML file named AndroidManifest.xml.

Launching a New Activity

As mentioned, an activity is the class that represents a screen displayed to the user. For an application that needs to navigate across multiple screens, multiple activity classes are required. So to enable a new screen, you start by adding a new Java class to the project, giving it its own layout and logic. Next, you must register the activity class in the manifest file, as shown in Listing 2.



    
    
    
    
    
        
        
        
        
    
    
    

The sample manifest requests two permissions and defines the FeedHunterActivity class as the primary activity—the startup activity—and RssFeedListActivity as a secondary activity launched only programmatically. Here's the code you need to launch an activity—for example, you can call the code in response to a click or a touch gesture.

private void goGetFeed() {
    Intent i = new Intent(this, RssFeedListActivity.class);
    startActivity(i);
    }

In Android, an intent is the description of an operation to be performed. The most significant of these actions is the launch of a new activity. The startActivity method defined on the Activity base class gets the intent that wraps up the type of the activity to launch and launches it. Activities are placed one on top of the other in a system-managed stack that users navigate through using the Back button. Activities in the stack are never rearranged, only pushed and popped from the stack as navigation occurs.

When you start a new activity using the startActivity method, the operation takes the form of a fire-and-forget action. If you want the original activity to receive data back from the spawned activity, then you use the startActivityForResult method instead. In this case, to receive data back from the launched activity, you have to override the method onActivityResult, as follows:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
   :
}

The data exchange takes place through the putExtra and getExtras methods of the Intent object. Methods operate on a dictionary, and the new activity stores data that the original will read back.

The Bottom Line

I hope you've seen from the example app we've covered here that the basic facts of Android programming are not hard to understand and apply. For .NET developers, mapping aspects of Android to known subjects is relatively easy. Such knowledge won't turn a novice Android developer into an expert right away, but at least it puts you in a good position to jump into developing Android apps.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish