January 7, 2012

Beginning Google Android Development for .NET Developers




So you’re interested in building applications for the Google Android mobile platform, but you’re a .NET developer.  What a perfect opportunity to dive head-first into – gasp – Java development!  Fear not – if you’ve never taken the plunge into anything outside of the warm, cozy Microsoft development platform, it’s not nearly as painful as many make it out to be.
This is the first post in a multi-part series on Android development for .NET developers.  Throughout the series, we’ll explore how to build applications for the Android platform and approach concepts in a way that’s familiar to .NET development.  This first post is an introduction to the Android SDK and the Eclipse IDE along with a high-level overview of Android applications.

PreRequisites

  • Java Development Kit (JDK) 6 – self-explanatory; the Java runtime and development libraries.
  • Eclipse – an IDE (integrated development environment) for Java and other languages.   If you don’t have it installed, grab the Eclipse IDE for Java Developers version, which will suit the needs of this tutorial.  The Windows download doesn’t contain an installer, so extract the ZIP in an accessible location, such as C:\eclipse.
  • Android Software Development Kit (SDK) – The heart of Android development.  This provides all of the necessary tools and libraries required to build applications for the Android platform.  Extract it to an accessible location on your hard drive and run the setup executable, which will download and install a set of components.
  • Android Development Tools (ADT) Eclipse Plugin – This plugin adds Android-specific development tools and project templates to Eclipse.  Instead of a separate download, it installs within Eclipse – you can follow the instructions here to get it installed.

Configuring the Android SDK and Creating Your First Project

Okay, take a deep breath – we’re ready to get started.  Launch Eclipse by navigating to your extracted folder and double-click on Eclipse.exe.
Before we jump into a project, we’ll need to configure the Android SDK preferences.  Select “Window” from the menu bar and choose “Preferences.”  Choose “Android” from the list on the left.  In the “SDK Location” field, navigate to the folder where you unzipped and installed the SDK and hit “Apply.”  You should see the list of SDK Targets get populated.  These targets are a list of Android platform versions that you can build on.  Unlike the iPhone, which has one standard set of hardware, the Android platform is open to various hardware manufacturers which use different versions that support different sets of functionality.  For example, the HTC Droid Incredible runs version 2.1, but the T-Mobile G1 only supports version 1.6.  We’ll address these differences later.  For now, just be aware that there are various versions of the platform and click “OK” to close the window.
Next, we’ll create our Android project.  The Android SDK comes with over twenty sample applications, so we’ll create a project using one of those to get acquainted with everything.  From the menu bar, choose “File” -> “New” -> “Project.”  The pop-up window that appears is similar to the “Create Project” wizard in Visual Studio – you’ll see a list of project templates that control how your project is initially set up.  In VS, you could select things like “ASP.NET Web Application” which would automatically configure your web server and add the Default.aspx and web.config files to the project.  Here, we’ll drill-down into the “Android” group and select “Android Project” which will add all of the necessary references to the Android SDK, among other things.  Once “Android Project” is selected, click “Next.”
Now we will set up the basic details of our project.  Under the “Contents” group, choose “Create project from existing sample.”  Then, from the “Build Target” list, select the “Android 2.0″ checkbox.   The “Samples” drop-down will populate with all of the sample applications that come with the Android SDK.  Choose “Snake,” which is a port of the classic game.  When you select it, the “Project Name” and “Properties” fields will automatically populate.  Click “Finish” and your project will be created.
New Android Project Wizard
Now that our project is created, let’s explore the Eclipse IDE.

Getting Familiar with Eclipse

When you create a project in Visual Studio, by default, the files will get put in the My Documents/Visual Studio 2010/Projects folder.  Similarly, Eclipse projects will get created in your “workspace.” The location of this gets specified when Eclipse is launched.  I keep my workspace in my User directory, at C:\Users\nathan.dudek\workspace.  However, since we chose an existing sample project, you won’t find the Snake project in your workspace on the filesystem.  Instead, it uses the existing files in the Android SDK’s “samples” directory.  In this case, you’ll find everything at the “\platforms\android-5\samples\Snake”.
In Visual Studio, we’re used to Project and Solution files, such as “Company.Application.proj.”  Eclipse also uses project files, but in every case, the filename is “.project.”  The context of the particular project is taken from the directory that it resides in instead of a descriptive filename.  Take a peek at the contents of this .project file in a text editor and you’ll notice it’s very similar to a .NET project file – XML describing various properties of the project.
We’re also used to the concept of “References” in Visual Studio – pointers to various assemblies and libraries that are utilized in the application.  Eclipse (actually, Java) handles this with a “Class Path”.  All references to outside libraries, such as JAR files (similar to DLLs), need to be included in this class path.  Eclipses stores these in the “.classpath” file alongside the .project file.
Let’s take a look at the Eclipse UI.  Eclipse is built on around an extremely powerful, pluggable architecture, so it can seem complex and confusing at first.  But, after navigating around a bit, you’ll find many tools that appear similar to the ones you’re used to in Visual Studio.  After all, the tools you need to build and debug an application, regardless of platform or language, are generally the same.
  • Package Explorer – Similar to the Solution Explorer in Visual Studio.  Let’s you navigate through the various files in your project.
  • Editor Window – tabbed, colored-syntax editor window.
  • Problems – Shows you build errors and warnings, similar to the Error List in Visual Studio.
  • Console – Shows you build messages and runtime output, similar to the Output window in Visual Studio.
  • Toolbar – You’ll see the buttons to debug, run, save, open, etc.
Eclipse IDE with Android Sample Project Snake
One other quick note about Eclipse before we jump into the Android application itself – by default, it will build the application automatically as you edit it.  It’s a handy feature to find problems as you create them!  I liken it to personalized continuous integration – immediate feedback that you broke the build.
Take a few moments to get familiar with the IDE. Ready to dive into Android code? Let’s go!
Note: Several readers have sent me a note saying that an error appears in the “Problems” window when the project is opened, stating that “Project ‘Snake’ is missing a required source folder: ‘gen’.” To fix this error, expand the “Snake” project in the “Package Explorer” window, then expand the “gen” folder along with the “com.example.andorid.snake” item below it.  Delete the file R.java by right-clicking on it and choosing “Delete.”  The file will immediately be regenerated and the error will disappear.  I haven’t discovered the cause of this yet; I don’t know if it’s a problem with Eclipse or the Android samples, but if I find out more I will update this post.

Exploring the Components of an Android Application

There are five key components that make up Android applications:
  • Activity – Activities represent your application’s user interface layer.  Each Activity represents a single action that a user can interface with.  It could be related to a Form.
  • Service – Services represent background tasks.
  • Broadcast Receiver – Broadcast Receivers react to announcements, similar to events.  An example of system-level announcement could be that the battery is low.  Applications (including your own) can also generate their own announcements.
  • Content Provider – Content Providers expose datasets from your application to other applications.  If our Snake sample application wanted to allow other applications to access the high scores, it could expose them in a Content Provider.
  • Intent – Intents are messages.  You can use intents to send messages to a specific Activity or Service, or send it to the entire system.
Each of these components are represented by Java classes – Activity, Service, BroadcastReceiver, ContentProvider, and Intent, respectively.  The classes that make up your application end up being subclasses of these base classes.  Java uses the “extends” keyword to perform inheritance.  So,
1
public class Snake extends Activity { ... }
in Java is basically the equivalent of
1
public class Snake : Activity { ... }
in C#.
Every Android application also has a “manifest” file which This is stored in the file AndroidManifest.xml, included with the Snake sample source.  The main purpose is to inform Android what components make up the application.
Our simple Snake sample application will only deal with a single Activity and none of the other components mentioned above.  Our Activity represents the Snake game that the user can play.  Let’s take a look at the source code by opening up the Snake.java file.  You can find it in the “Package Explorer” window by drilling down to Snake -> src -> com.example.android.snake -> Snake.java.
You’ll notice the file is only 83 lines long.  That’s because this file simply represents the Android Activity – the actual Snake game logic is contained in the SnakeView.java file.  Here are the key things to note about Snake.java:
  1. It’s a subclass of Activity.
    1
    public class Snake extends Activity
  2. Three methods from the Activity base class are overridden, as noted from the @Override keyword (same as the override keyword in C#):
    1
    public void onCreate(Bundle savedInstanceState)
    1
    protected void onPause()
    1
    protected void onSaveInstanceState(Bundle outState)
    These three overrides handle the events that the method names state – when the activity is created, when the game is paused, and when the application state is saved.
  3. This Snake class relies heavily on the SnakeView class, which you can also find in thesrc folder.  SnakeView is a subclass of another very important Android class – View.  Views are used by Activities to draw things to the screen and handle user interaction.  Since we’re just trying to demonstrate the Android specific components of this application, just understand that SnakeView handles all of the details of user keystrokes, drawing and animating the snake to the screen, etc.
Let’s run the application and see how it launches.

Launching the Application in the Simulator

From the menu bar, click Run ->Run.  You’ll get a message stating “No compatible targets were found.  Do you wish to add a new Android Virtual Device?”  Click yes to set up the Android simulator.
Since we chose Android 2.0 as our platform during the project setup, we’ll create an Android 2.0 virtual device.  Enter a device name such as “Android2.0″ and choose “Android 2.0 – API Level 5″ from the Target drop-down list.  Then click the “Create AVD” button to complete the setup.
Android Virtual Device Setup
Click Run -> Run again to launch your application in the simulator.  The first run may take several minutes to load the virtual device, so don’t be alarmed if your application doesn’t launch immediately.  Once it finishes loading, your Snake game will appear on the screen.
Snake in Android Virtual Device
You can use the on-screen buttons to interact with the simulator, or you can use the buttons on your physical keyboard.  You can also interact with the rest of the Android platform by using the Home, Menu, Back, and Search buttons.

Next Steps

It’s worth exploring the samples provided with the Android SDK.  They cover many aspects of the available functionality, such as voice recognition, gaming, BlueTooth, gestures, and graphics.  In the next post, we’ll create an Android project from the ground up and create our first basic application.  In the meantime, dive deeper into the Snake source code and its SnakeView.java file if you want to see how the game logic and drawing engine works.  Also, take the time to get familiar with the Eclipse IDE.  After a little playing around, you’ll find it’s a pretty comfortable (and powerful) IDE.