Sunday, November 06, 2011

Creating your First Mono for Android Application

From a .Net Developer's Perspective


I will be showing you how to create the same application that was shown in the tutorial titled 'Creating your First Android Application'. Over time, I will create more advanced Android application development tutorials using both the Mono for Android (using C#) and Eclipse Android Plugin (using Java) frameworks.


Getting the Environment Setup
  1. Install the Java 1.6 JDK.
  2. Install the Android SDK from http://developer.android.com/sdk/index.html. I installed Android SDK revision 15.
    1. Do not use any spaces in the installation path. I used C:\AndroidSDK.
    2. Leave the 'Start SDK Manager' checkbox checked.
    3. Ensure that the 'Android SDK Tools' and ''Android SDK Platform-tools' are fully installed.
    4. I also installed 'Android 2.2 (API 8)' and 'Android 2.3.3 (API 10)'.
    5. Click on the 'Install N packages...' when ready.
    6. Check the 'Accept all' radio button, then click on 'Install'. It will download and then install the packages. Please note that this download & installation process takes a long time to complete. Don't worry if the log shows an "'adb kill-server' failed -- run manually if necessary." error message. This is simply the package manager's attempt to stop the Android Debug Bridge's server process, which is not yet/already running.
    7. Click 'Yes' to restart ADB.
    8. Close the SDK manager.
  3. Configure the Android Simulator:
    1. Open up the Android SDK AVD Manager.
    2. Click on 'New...'.
    3. Enter MonoDroid in the 'Name' field.
    4. In the 'Target' drop-down, select 'Android 2.2 - API Level 8'.
    5. Choose 512MB for the 'SD Card' 'Size'.
    6. Select 'HVGA' as the 'Built-in' 'Skin'.
    7. In the 'Hardware' section, click on the 'New ...' button.
    8. Select the 'Device ram size' property from the drop-down list.
    9. Click on 'OK'.
    10. Enter 512 for the 'Device ram size' property.
    11. Click on 'Create AVD'. It will take about a minute to complete.
    12. Close out of all Android SDK windows.
  4.  Install the 'Mono for Android for Windows' SDK from http://xamarin.com/trial. I've installed the Mono for Android SDK v1.2.
    1. If you get a message saying that Android SDK 14 is required, don't worry about it.
    2. Click on 'Next'.
    3. Close the installer.
Creating the First, Hello World Android Application
  1. Open up Visual Studio 2010.
  2. Choose the option to create a new project.
  3. In the 'Visual C#' tree, select 'Mono for Android Application'.
  4. Name the project DotNetFun.Android.HelloWorld.
  5. Click on OK.
  6. Rigkt-click on the 'DotNetFun.Android.HelloWorld' project, then click on 'Properties'.
  7. Click on the 'Android Manifest' tab.
  8. Click on the link to add an 'AndroidManifest.xml' file.
  9. Name the 'Application' Hello World.
  10. Name the 'Package' DotNetFun.Android.HelloWorld.
  11. Enter 1 for the 'Version number'.
  12. Enter v1 for the 'Version name'.
  13. Select 'API Level 8 - Android 2.2' in the 'Minimum Android version' drop-down.
  14. Save the project.
Dissecting the 'Mono for Android Application' Application


The Mono for Android folks have done a great job of recreating the look and feel of a typical Java and Eclipse based Android application in Visual Studio with their various templates, so kudos to them for a job well done.


The following is a summary description of the various aspects of a typical Android and Mono for Android Visual Studio application:
  • Android Activities
    Android Activities are akin to ASP.NET Web Form pages, ASP.NET MVC views, and Windows Forms forms. They are the screen areas where UI elements are rendered and interaction between the user and the application typically take place. Just like web forms and Windows forms raise events and have life-cycles, so, too, do Android Activities. The default Activity1.cs class file that's created when creating a new 'Mono for Android Application' application derives from the Android.Views.Activity class to provide base activity functionality, much like web forms pages typically derive from System.Web.UI.Page and Windows forms derive from System.Windows.Forms.Form. And much like web forms and Windows forms raise events and call event handlers, such as Init and PreRender, so, too, do Mono for Android Activities, such as the overridable OnCreate and OnStart methods respectively. For more about activities as used in Mono for Android, read Xamarin's 'Mono for Android Activity Lifecycle' documentation here: https://docs.google.com/open?id=1nTEo_ZLGWG4oTb6aUtZspVpPYRQzskyONr6g5iUPwKFqIG7Lpcuka-a1Y7FH For more about Android activities, visit this URL: http://developer.android.com/reference/android/app/Activity.html
  • Android Layouts
    Android layouts define how visual elements in an Activity are displayed. Layouts are Views per se (read below). Android supports the following layouts: FrameLayout, LinearLayout, TableLayout, and RelativeLayout. Layouts can be created either decoratively, using XML, or via code, using layout classes. The default 'Mono for Android Application' uses the declarative model, uses the LinearLayout, and is defined in the 'Main.axml' file, inside of the project's 'Resources\Layout' folder. For more about Android layouts, visit this URL: http://developer.android.com/guide/topics/ui/declaring-layout.html
  • Android Views
    Android views are basic UI controls that represent visual elements in activities that render content, handle UI interaction events, etc. They are akin to the typical.Net controls, such as buttons, text labels, checkboxes, etc. Some examples of Android views are the Button, CalendarView, CheckBox, DatePicker, EditText, GridView, LinearLayout, and TableLayout. TheViewGroup is a view that only holds other views. It's analogous to the .Net Panel control. The default 'Mono for Android Application' template comes with a Button view. Views can be included in the application either declaratively or via objects in code. For more about Android views, visit this URL: http://developer.android.com/reference/android/view/View.html
  • Resources
    Android and the Mono for Android framework support storing information in XML resource files. The Mono for Android framework generates designer class files that reflect these resources. Each type of resource is located in the project's 'Resources' folder. The 'Mono for Android Application' template does a good job of providing these resources via the Resource.Designer.cs designer-generated class file. Rather than reading an explanation about how resources work, take a look at figures #1 - #4 below for a more visual explanation. For more information about leveraging XML based resources, visit this URL: http://developer.android.com/guide/topics/resources/index.html
  • Activity1.cs
    This activity class is created by default when adding a new 'Mono for Android Application'. In its 'OnCreate' method, you'll see code that sets the content to be rendered in the Android Activity as well as an event handler to handle a button click. Each time this button is clicked, the button's caption is updated to the number of times it's been clicked.
Fig. 1

Fig. 2
Fig. 3
Fig. 4

Deploying & Testing the Mono for Android Application
  1. Press the F5 key to debug and deploy the application to the Android simulator created earlier.
  2. In the 'Select Device' dialog box, click on the 'Start emulator image' link.
  3. Do NOT choose any of the simulators created by the Android SDK.
  4. Select the 'MonoDroid' simulator created earlier.
  5. Click on 'OK'. Wait for the 'Select Device' dialog box to show the emulator in the list. During this time, it will seem as is nothing's happening. Don't worry, something is.
  6. The emulator will be setup on port, so the next screen you will see is the same 'Select Device' dialog box, except, you'll now see an emulator listed that's titled something like emulator-5554. Click on the OK to select the emulator and get the application deployed.
  7. The first time the emulator is deployed, the Mono for Android framework takes some time to package the application for use with the simulator, install the Mono runtime and platform framework, etc, so please be patient. During this phase, it might seem like nothing's going on, but take a look at the Visual Studio status bar. It will show 'Deploy started...'. While this is the status, let the process proceed, even though you see the actual emulator in another window. This process can take up to 10 minutes to complete. Each time the project changes, the framework will detect this and re-package and deploy the application, so prepare for some ample wait times accordingly.
  8. Eventually, the application is deployed (if no errors were encountered, that is). Drag the unlock button in the emulator to the right to unlock the Android.
  9. Click on the application button.
  10. Click on the application to launch it. It will take a few seconds for the application to load. It's ready when you can see the 'Hello World, Click Me!' button.
  11. Click on the button to test the application.
  12. Close the emulator window.
Let's Change Some Things

The application's name isn't very unintuitive, so let's change it. There are several ways to set the application's name: via 1) the Visual Studio property pages, 2) editing the 'AndroidManifest.xml' file, and 3) the main class' Activity attribute's Label property.

Setting the Application Name via the Main Class' Activity Attribute
  1. Open up the 'Activity1.cs' class file.
  2. Change the Activity attribute's Label property to "App Name via Label Property".
  3. Press F5 to test the new name.
Setting the Application Name via the Visual Studio project's Property Pages

When the main class' Activity attribute's Label property is set, that label will override whatever the application's name is set to in other areas.
  1. Remove the main class' Activity attribute's Label property, entirely.
  2. Right-click on the project, then click on 'Properties'.
  3. Click on the 'Android Manifest' tab.
  4. Change the 'Application name:' to App Name via Prop Pages.
  5. Press F5 to test the new name.
Setting the Application Name via the AndroidManifest.xml File


Setting the application name via the VS property pages simply results in the 'AndroidManifest.xml' file's application element being changed.
  1. Open up the 'AndroidManifest.xml' file in the 'Properties' folder in Visual Studio.
  2. Locate and the 'application' element and change the 'android:label's string to App Name via AndroidManifest.xml.
  3. Press F5 to test the new name.
Saving Strings in the Strings.xml Resource File


You can save strings in the 'Strings.xml' resource file and retrieve them at runtime via code. Let's create a new string resource for the Hello Button's Text property.
  1. Open up the 'Strings.xml' file in the 'Resources\Values' folder.
  2. Add the following XML element within the 'resources' element:

    <string name="HelloButtonText">Button Text via Strings.xml</string>

  3. Press F6 to compile the application. This will result in the 'Resource.Designer.cs' class being updated to reflect the new string resource.
  4. Open up the 'Activity1.cs' class file.
  5. Add the following line to the end of the 'OnCreate' method:

    button.Text = this.GetString(Resource.String.HelloButtonText);

  6. Press F5 to test the changes.
Adding UI Elements Declaratively
  1. Open up the 'Main.axml' layout resource file in 'Resources\Layout'.
  2. Add the following element inside of the 'LinearLayout' element:

    <Button
          android:id="@+id/DialogButton"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Dialog Button"
        />
    
    
  3. Press F6 to compile the project in order for 'Resource.Designer.cs' to get updated.
  4. Open up the 'Activity1.cs file'.
  5. Add the following code to the end of the 'OnCreate' method:

    var dialogButton = FindViewById<Button>(Resource.Id.DialogButton);
    dialogButton.Click += delegate 
    {
                    var builder = new AlertDialog.Builder(this);
                    builder.SetMessage("Hello, World!");
                    builder.SetCancelable(false);
                    builder.SetPositiveButton("OK", delegate {  });
                    var dialog = builder.Create();
                    dialog.Show();
    };
    
    
  6. Press F5 to test your changes.

Adding UI Elements Using Code



  1. Remove the Button element you added to the 'Main.axml' file earlier.
  2. Open up the 'Activity1.cs' class file.
  3. Remove the dialogButton line of code added earlier and replace it with the following code:

    var dialogButton = new Button(this);
                dialogButton.Text = "Dialog Button";
    
    
  4. Press F5 to test your changes. The results should be exactly the same. Instead of using the XML based Button, however, we created the button via the runtime code.
That about does it for this tutorial. Be on the lookout for more!

2 comments:

Android app development said...

This is one of the Interesting post.Your blog is providing good Entertainment.This is one of the unique post.
Android app developers

EeKay said...

Nice introduction, especially the generic explanation with links helped me out.

one note: halfway the "Android Layouts" bullit you mention "either decoratively, using XML, ..." but i guess it should be Declaratively. This confused me until later in the article where you say "Declaratively". I guess all interface elements are decoratively ;)