Xamarin Mobile Application Development for Android

By Mark Reynolds
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. The Anatomy of an Android App

About this book

Technology trends come and go, but few have generated the excitement, momentum, or long-term impact that mobile computing has. Mobile computing impacts people’s lives at work and at home on a daily basis. Many companies and individual developers are looking to become a part of the movement but are unsure how to best utilize their existing skills and assets. The Xamarin suite of products provides new opportunities to those who already have a significant investment in C# development skills and .NET code bases, and would like to enter into this new, exciting world.

This example-oriented guide provides a practical approach to quickly learning the fundamentals of Android app development using C# and Xamarin.Android. It will lead the readers through building an Android app step-by-step with steadily increasing complexity.

This book begins with an overview of the Android and Xamarin platforms to provide you with a solid understanding of the environment you will be working in. You will then be gradually walked through building and testing an Android app using C# and the Xamarin.Android product. You will learn the basics of interacting with some of the more interesting aspects of Android devices including location services, the camera, and maps. You will also be given the opportunity to work with three different layout managers to gain an understanding of the various options available for arranging controls and content. The book ends with a discussion on the final steps involved in preparing apps for deployment to the various Android app stores.

In a relatively short period of time, developers familiar with C# and rich client technologies such as WPF and Silverlight will be effectively developing, testing, and delivering Android apps.

Publication date:
January 2014
Publisher
Packt
Pages
168
ISBN
9781783559169

 

Chapter 1. The Anatomy of an Android App

While most of this book will be focused on learning how to develop Android apps using C# and Xamarin.Android, we will start with a more general discussion of Android. What is Android? How does Android facilitate the task of creating great mobile apps? The Anatomy of an Android App will help to answer these questions by providing a base-level understanding of the following topics:

  • The Android platform

  • Android applications (Building Blocks)

 

The Android platform


The Android platform has been one of the most successful platforms developed in recent years and provides developers with many services and features required to create rich mobile applications. The following diagram provides a high-level view of how the Android platform is organized, and the subsequent sections provide a brief description of each major component:

Linux

Android is a Linux-based operating system designed primarily for mobile devices such as smartphones and tablets. The latest versions of Android are based on Linux kernel Version 3.x (Version 2.6 for versions prior to Android 4.0).

Native libraries

Android is delivered with a set of native libraries written in C/C++, which provide various types of services. These libraries predominantly come from the open source community.

The Android runtime

Android apps run within the Dalvik Virtual Machine (Dalvik VM), which is similar to a Java VM but has been optimized for devices with limited memory and processing capacity.

Android apps are initially compiled to the Java byte code using the Java compiler, but they have an additional compilation step that transforms the Java byte code to the Dalvik byte code, suitable to run within the Dalvik VM.

Dalvik is delivered with the Android core libraries. These libraries do not align with a specific Java platform (JSE, JEE, or JME) but rather act as a hybrid platform most closely aligned with JSE, minus the user interface-focused components AWT and Swing. The Android Application Framework (AAF) provides an alternate means of creating user interfaces.

The Application Framework

The Application Framework is the part of the Android platform, most familiar to developers. It is delivered as a set of Java libraries and allows you to build user interfaces, interact with device capabilities such as the camera or location services, load and work with various types of application resources, and perform many more useful tasks.

Applications

At the top of the stack sits the humble application, the component that actually delivers value to the user. Android comes with a set of applications that provide base functionality such as managing contacts, using the phone, checking email, and browsing the Web. The key to Android's success is the vast array of third-party applications that can be installed, which allow users to do things such as stream live sports' events, edit a movie captured on the phone, interact with friends through their favorite social media site, and much more.

The Android packages (.apk)

Applications are delivered for installation in an Android package format. An Android package is created as the result of compiling an Android app and is an archive file with a .apk extension. An Android package contains all of the code and the supporting files required to run a single application including the following:

  • Dalvik executables (*.dex files)

  • Resources

  • Native libraries

  • The application manifest

Android packages can be installed directly via e-mails, URLs, or memory cards. They can also be installed indirectly through app stores such as Google Play.

The application manifest

All Android applications have a manifest file (AndroidManifest.xml) that tells the Android platform everything it needs to know to successfully run the application, including the following:

  • Minimum API Level required by the application

  • Hardware/software features used or required by the application

  • Permissions required by the application

  • The initial screen (Android activity) to start with when the application is launched

  • Libraries, other than AAF, required by the application

  • And so on

Versions of Android

Identifying the version of the Android platform can be somewhat confusing; there is a version number, API level, and nickname, and these are sometimes used interchangeably.

The version number represents a release of the platform. Sometimes, a new release is created to deliver new capabilities, while sometimes it is created to fix bugs.

The API level represents a set of capabilities. As the API level increases, new capabilities are delivered to the developer.

The following table lists the versions of the platform in the reverse chronological order:

Platform version

API level

Nickname

Released

4.4

19

KitKat

10/31/2013

4.3

18

Jelly Bean

07/24/2013

4.2, 4.22

17

 

11/13/2012

4.1, 4.11

16

 

07/09/2012

4.0.3, 4.0.4

15

Ice Cream Sandwich

12/16/2011

4.0, 4.01, 4.02

14

 

10/19/2011

3.2

13

Honeycomb

07/15/2011

3.1.x

12

 

05/10/2011

3.0.x

11

 

02/22/2011

2.3.3, 2.3.4

10

Gingerbread

02/02/2011

2.3, 2.3.1, 2.3.2

9

 

12/06/2010

2.2.x

8

Froyo

05/20/2010

2.1.x

7

Éclair

01/12/2010

2.0.1

6

 

12/03/2009

2.0

5

 

10/26/2009

1.6

4

Donut

09/15/2009

 

The Android applications


Now, let's spend some time discussing applications—those things we write that provide value to the user. Android applications are made up of various types of classes and resources. The following sections describe the different types of classes or building blocks that an application can be composed of.

Activities

One of the most fundamental parts of an Android application is an activity. An activity provides a single function that a user can perform with an application such as list contacts, enter new contact, and display location(s) on a map. A single application is composed of many activities.

A user interacts with an activity through one or more Views, which are described later in this chapter. If you are familiar with the Model-View-Controller pattern, you would have noticed that activities fulfill the role of the Controller.

The life cycle of an activity

Activities have a well-defined life cycle that can be described in terms of states, transitions, and events. The following diagram provides a graphical view of the life cycle of an activity:

The states of an activity

The states depicted in the previous diagram are derived, meaning there is no "State" variable on an activity that explicitly identifies one of these states, but the state is implied and useful for discussion. The following table describes the behavior of an activity based on its state:

State

Description

Running

The activity has been created and initialized, and is visible and available to the user for interaction.

Paused

The activity view is being partially blocked by another activity.

Stopped

The activity is no longer visible to the user, The activity has not been destroyed, and state is retained but it is placed in the background and no processing is allowed.

The events of an activity

During the transition between states, a series of events are called on the activity. These events provide developers a platform for various types of processing.

Event

Called

Typical processing

onCreate

When an activity is created, generally from a user choosing to start the app

  • Create Views

  • Initialize variables

  • Allocate long-lived resources

onStart

After onCreate or onRestart and right before an activity becomes visible to the user

  • Allocate resources

onResume

Before an activity is ready to start interacting with a user

  • Initialize UI widgets for viewing

  • Starting animations or videos

  • Start listening for GPS updates

onPause

When an activity's view has become partially blocked and is not the focus of input

  • Commit unsaved updates

  • Pause animations or videos

  • Stop listening for GPS updates

onStop

When an activity's view is no longer visible to the user

  • Release resources

onRestart

An activity is being placed back in the foreground, generally because the user has selected the back button

  • Allocate resources

onDestroy

Before the activity is destroyed

  • Cleanup resources that may have been allocated in onCreate

Something that is not obvious to developers new to Android is the way the framework deals with device orientation changes. By default, when the orientation of a device is changed from portrait to landscape, Android destroys and recreates existing activities to help ensure that the most appropriate layout is used. Unless this behavior is planned for, it can be very disruptive to processing. If needed, this behavior can be overridden and activities can be retained. We will discuss special considerations in dealing with state and other processing concerns related to this topic in Chapter 7, Making POIApp Location Aware.

Services

Services are components that run in the background to perform long-running operations with no direct user interface. Services may load data into a cache, play music, or perform some other type of processing, while a user interacts with other activities uninterrupted.

Content providers

Content providers manage access to a central repository of data such as contacts. A content provider is a part of an application, which usually provides a user interface to manage its data. A standard interface is also provided, which allows other applications to access its repository.

Broadcast receivers

Broadcast receivers are components that perform some type of processing in response to system-wide broadcasts. Broadcasts are generally initiated by the system for events such as low battery, taking a picture, or turning on Bluetooth. Applications may also choose to send broadcasts; a content provider might send a broadcast when data, such as a contact, has been updated. While broadcast receivers do not have a user interface, they may indirectly cause updates to a status.

Views and ViewGroups

Everything that you see in an Android app is a View; buttons, labels, text boxes, and radio buttons are all examples of Views. Views are organized in a hierarchy using various types of ViewGroups. A ViewGroup is a special kind of View which is used to arrange (layout) other Views on the screen.

Declarative versus programmatic View creation

Views and ViewGroups can be created using two different methods, programmatically or declaratively. When using a programmatic approach, a developer makes API calls to create and position each individual View in the UI. When using a declarative approach, a developer creates XML layout files that specify how Views should be arranged. The declarative method enjoys several advantages stated as follows:

  • Provides better separation of the visual design of an application from the processing logic

  • Allows multiple layouts to be created to support multiple devices or device configurations with a single code base

  • Development tools, such as Android Studio and the Android plugin for Eclipse, allow you to view the user interface as you build it, without needing to compile and execute your application after each change

While I prefer the declarative method for most things, I have found that, in practice, some combination of programmatic and declarative methods are often required.

User interface widgets

Android provides a comprehensive set of user interface widgets that can be used to build a rich user experience. All of these widgets are subtypes of View and can be organized into sophisticated layouts using various types of ViewGroups. All of the user interface widgets can be found in the android.widget package within the Application Framework.

Common layouts

The Application Framework has a number of subclasses of ViewGroup, each of which provides a unique and useful way of organizing content.

The previous diagram depicts a few of the more common layouts, each of which can be used for specific needs.

Layout

Description

Scenario

Linear layout

Organizes its children into a single horizontal or vertical row and creates a scrollbar when required.

Use when a widget positions flow horizontally or vertically.

Relative layout

Organizes child objects relative to each other or to the parent.

Use when widget positions can best be described in relationship to another widget (to the left of) or the boundary area of the parent (right side, centered).

Table layout

Organizes its children into rows and columns.

Use when widget positions would naturally fit into rows and columns. Great when multiple columns of entry and labels are needed.

For complex layout scenarios, Android allows layouts to be nested. Deeply nested layouts can impact performance and should be avoided if possible.

Adapter layouts

For layouts that are driven by a dynamic data source, the Application Framework has a set of classes derived from AdapterView.

The previous diagram depicts two of the most common adapter layouts.

  • List View: Organizes content from the data source into a scrolling single column list

  • Grid View: Organizes content from the data source into a grid of columns and rows

XML layout files

To create a UI using a declarative method, Android provides an XML vocabulary with tags that define the various types of elements that can compose a View. The concept behind Android XML layout files is very similar to the way HTML tags are used to define web pages or Microsoft's XAML tags are used to define WPF (Windows Presentation Foundation) user interfaces. The following example shows a simple View using a linear layout and containing a search entry field and search button:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <TextView
    android:text="Enter Search Criteria"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/searchCriteriaTextView" />
    <Button
      android:text="Search"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:id="@+id/searchButton" />
</LinearLayout>

Element and attribute names

Care has been taken to aligning the names for elements and attributes in the XML vocabulary with class and method names from the Application Framework. In the previous example, the element names LinearLayout, TextView, and Button correspond to class names in the Application Framework. Likewise, in the Button element, the android:text attribute corresponds to the setText()setter on the Button class.

IDs

Each View can have a unique integer ID associated with it and can be used to reference the View from within an application's code. In the XML file, the ID is specified as a user friendly text name. For example, consider the following line of code:

android:id="@+id/searchButton"

In this example, the @ operator tells the parser that it should treat the remainder of the string as an ID resource; the + symbol tells the parser that this is a new resource name that should be added to the resource file, R.java. The resource file defines integer constants that can be used to reference resources.

Using XML layouts from activities

XML layouts can easily be loaded by an application at runtime. This task is generally performed from within the onCreate() method of an activity using the setContentView() method. For example, consider the following line of code:

setContentView(R.layout.main);

Intents

Intents are messages that can be sent to the various types of components in an Android App in order to request some type of action to be performed. Intents may be used to accomplish any of the following:

  1. Start an activity with the option of receiving a result.

  2. Start or stop a service.

  3. Notify the component of conditions like low battery or time zone change.

  4. Request an action from another app, such as request the map app to display a location or request that the camera app take a picture and save it.

Resources

Creating an Android application involves more than simply writing code. A rich mobile app requires things such as images, audio files, animations, menus, and style, just to name a few. The Application Framework provides APIs that can be used to load and utilize the various types of resources with your Android apps.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com . If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The R.java file

Resources are generally referenced from within an application using an integer constant that is automatically assigned when the resource is added to the project and compiled. These constants are placed in a Java source file named R.java. The following example shows the R.java class from a simple application:

public final class R {
  public static final class attr {
  }
  public static final class drawable {
    public static final int icon=0x7f020000;
  }
  public static final class id {
    public static final int myButton=0x7f050000;
    public static final int searchButton=0x7f050002;
    public static final int searchCriteriaTextView=0x7f050001;
  }
  public static final class layout {
    public static final int main=0x7f030000;
    public static final int search=0x7f030001;
  }
  public static final class string {
    public static final int app_name=0x7f040001;
    public static final int hello=0x7f040000;
  }
}
 

Summary


In this chapter, we have tried to provide a concise and adequate description of the Android platform and the application's building blocks. In the next chapter, we will turn our attention to Xamarin.Android and the facilities it provides to allow for Android development with .NET and C#.

About the Author

  • Mark Reynolds

    Mark Reynolds is a software enthusiast who has worked in the industry for nearly 30 years. He began his career with Electronic Data Systems, building and supporting systems for the manufacturing sector. Over the years, Mark has worked with start-ups and Fortune 100 companies across a diverse set of industries. In 1993, he started a consulting practice that focused on delivering training and mentoring services in the areas of software architecture, design, and implementation. With the rise of mobile computing, he has focused his practice on designing, developing, and delivering mobile software solutions.

    Mark recently published his first book, Xamarin Mobile Application Development for Android, Packt Publishing. His private consulting practice is based in Allen, TX, USA, where he resides with his wife and son.

    Browse publications by this author
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial