We live in an age where technologies are being developed and have become more and more accessible than ever before. The rise of the mobile computing platform has taken the technology evolution to a new high. The phones and tablets are getting smarter day by day and becoming the alternatives to a traditional PC. In this fiercely competitive world of mobile computing, every traditional PC manufacturers to small start-ups are in the race brining the devices of various form factors.
In this book, we will show you how to take advantage of your existing C# skills to write applications that run on Android powered devices. 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? This chapter will help you answer these questions by providing a base-level understanding of the following topics:
An overview of the Android platform
Android platform versions and feature releases
Android applications (building blocks)
The Android platform has been one of the most powerful, evolving, and advanced mobile operating systems developed in recent years, which provides various services and features, that helps developers to build rich mobile applications. Android is an open source operating system currently developed and maintained by Google. Due to its open source nature, it has a larger community base of developers and device manufacturers.
The Android operating system was primarily designed for low powered computing phones, but later, its base was widen to various form factors, including smartphones, tablets, Android TV, and Wearables.
The Android operating system has evolved with a series of frequent updates since its initial beta release in November 2007. 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 is an integer value that represents a set of capabilities. As the API level increases, new capabilities are delivered to the developer.
The following table lists all the major Android platform releases in the reverse chronological order:
The Android platform is comprised of applications, operating systems, runtime, middleware, services, and libraries. The following diagram provides a high-level view of how each layer in the Android platform is organized, and the subsequent sections provide a brief description of each major component:

Android is a Linux-based operating system designed and customized primarily for mobile devices, such as smartphones and tablets. Positioned at the bottom of the Android stack, the Linux kernel provides the interface between device hardware and Android software layers. The latest versions of Android are based on the Linux kernel version 3.4 or above (version 2.6 for versions prior to Android 4.0).
The Linux kernel provides some of the core system services such as memory management, process and task management, power management, networking stack, and various device drivers to interact with the device hardware.
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 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.
The 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 using a process called the Just in Time (JIT) compilation. The output produced by the JIT compiler is 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.
Although Dalvik worked pretty well, the downside is that there is a huge lag every time the application is launched. That's where the new virtual machine, ART, comes in.
ART is precursor to Dalvik. It is the new application runtime introduced in Android 4.4 (KitKat) as a new experimental runtime environment and is implemented fully in Android 5.0 (Lollipop). This is primarily designed for performance and an improved app start up time. The primary difference between ART and Dalvik is the compilation approach. While Dalvik uses JIT, ART employs a new concept called Ahead-of-Time (AOT). What this means is that new apps are getting compiled during installation, before they are even launched. To learn more about ART, you can refer to https://source.android.com/devices/tech/dalvik/.
The application framework is the part of the Android platform, which is 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. Here are some of the major services:
ActivityManager: This service is responsible for the activity life cycle, state management, and controls the activity stack. Later, in this chapter, we will learn more about the activity life cycle.
WindowManager: This service is responsible for managing the z-order list of screens. Each activity is attached to a window that is used to display the content on the screen, which is controlled by
WindowManager
.Content providers: This provides an interface to publish and share data between applications.
View system: This provides a set of UI controls to build an application user interface.
NotificationManage: This service manages application alerts and notifications.
Resource Manager: This service provides access to resources, such as user interface layout, strings, color, dimensions, and so on.
PackageManager: This holds the metadata of all the installed applications on the device.
TelephonyManager: This provides information on the telephone services available on the device, such as status and subscriber information, to the application.
LocationManager: This provides access to system location services.
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 e-mails, 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.
Now, let's spend some time discussing applications—those things we write that provide value to the user. The Android applications are made up of various types of classes and resources. The following sections describe the different building blocks that an application can be composed of.
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 an .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
The 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.
All the 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 such as location or camera
The initial screen (Android activity) to start with when the application is launched
The ability to install the application in the external memory
Libraries, other than AAF, required by the application and so on
One of the most fundamental parts of an Android application is an activity. An activity represents a single screen with a user interface through which a user can interact with the application. A single application is composed of many activities. For example, a phone book application can have multiple activities representing different functions, such as list contacts, add contacts, capture contact photos, and so on.
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 (MVC) pattern, you would have noticed that the activities fulfill the role of the controller.
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 depicted in the preceding diagram are derived, which means that 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 |
---|---|
|
The activity has been created and initialized and is visible and available to the user for interaction. |
|
The activity view is being partially blocked by another activity. |
|
The activity is no longer visible to the user. The activity has not been destroyed, and the state is retained but it is placed in the background and no processing is allowed. |
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. The following table describes the different event callbacks and typically, the processing done in the application during each callback:
Event |
Called |
Typical processing |
---|---|---|
|
When an activity is created, generally from a user choosing to start the app |
|
|
After |
|
|
Before an activity is ready to start interacting with a user and immediately after the |
|
|
When an activity's view has become partially blocked and is not the focus of input |
|
|
When an activity's view is no longer visible to the user |
|
|
An activity is being placed back in the foreground, generally, because the user has selected the back button |
|
|
Before the activity is destroyed |
|
Something that is not obvious to developers and 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 for the current device orientation.
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 6, Making Your App Orientation-aware.
A fragment is a reusable user interface component, introduced since Android 3.0 (API level 11), and is primarily intended to build dynamic and modular user interfaces for different screen sizes. A fragment is always embedded in an activity, and like any other view, it lives in a ViewGroup
(ViewGroups are explained in more detail later in this chapter) inside the view hierarchy. Like an activity, a fragment defines its own layout and has its own life cycle callbacks. When designing your application to support multiple form factors, fragments can be reused to optimize the user experience based on the available screen space.
Let's examine how fragments can be used to develop a modular user interface with the following example.
The following figure depicts the wireframe of a newsreader application, designed to work on both smartphone and tablet devices. As a tablet has more screen space, the news list and the details are presented as split views in a single activity, whereas the phone uses two different activities for this:

The Android smartphone uses two activities: ActivityA containing FragmentA is used to show the news list and ActivityB containing FragmentB is used to show the details of the selected news. In a tablet, we have a single activity ActivityA that contains both FragmentA and FragmentB.
As you can see here, FragmentA and FragmentB are the same implementation and are reused in different layout configurations to provide a different user experience on both the phone and tablet.
Unlike the activity life cycle, understanding the fragment life cycle can be a bit tricky. In the following section, we will dig more into the fragment behavior and its life cycle methods.
The Android fragment has its own life cycle method, which is very similar to an activity. It contains all of the activity life cycle methods and is supplied with some additional callback methods. Fragments are always embedded in an activity, so its callbacks are directly affected due to the host activities' life cycle. For example, if the host activity receives onStop()
, all the attached fragments also receive the onStop()
callback.
The following diagram provides a graphical view of the fragment life cycle:

Let's take a look at each of the fragment life cycle events that gets called:
onInflate
: This event is called only if we define a fragment directly in an activity layout using thefragment
tag, and while the content view of the activity is being inflated (typically, whensetContentView()
is called on an activity). This method passesAttributeSet
that holds all the fragment attributes passed from thefragment
tag. These attributes can be stored for later use. At this stage, the fragment is not even associated with an activity, and hence, we cannot perform any user interface-related tasks.onAttach
: This is called once the fragment instance is associated with an activity.onCreate
: This event is called afteronAttach
and beforeonCreateView
; when the fragment instance is created or recreated. At this point, the base activity that holds this fragment is in the process of being created. At this point, you may use a background thread to get data for the fragment to use.onCreateView
: At this point, the fragment instantiates its user interface and loads the view object hierarchy it contains. This method passes three arguments:LayoutInflater
,ViewGroup
, andbundle
. TheLayoutInflater
argument can be used to inflate any layout for a fragment. Abundle
specifies whether the fragment is created freshly or recreated. If it is recreated from the previous saved state, then the bundle will be non-null.onActivityCreated
: This method is called when the activity that contains the fragment has been created, and the fragment's view hierarchy is instantiated. At this point, you can access the view by its ID using thefindViewById()
method and make any changes before it is visible to the user.onStart
: This method is tied to the activityonStart()
callback and is called when the fragment becomes visible to the user. At this point, the fragment is visible but not available for user interaction just yet.onResume
: This method is called before the fragment is ready to start interacting with a user. At this point, the fragment is said to be running and the user is free to perform any operations on the app.onPause
: This method is tied to the activityonPause()
callback and is called when the fragment is taken out of the foreground.onStop
: This method is tied to the activityonStop()
callback and called when the fragment is not visible.onDestroyView
: This method tells the fragment that the view created fromonCreateView()
is now detached from the fragment. This callback is called afteronStop()
and before theonDestroy()
method.onDestroy
: This method is called when the fragment is no longer in use. This is called afteronStop()
and beforeonDetach()
.onDetach
: This method is called afteronDestroy()
, and when the fragment is no longer attached to an activity.
Services are application components that run in the background to perform long-running operations with no direct access to the user interface. A typical long-running task can be periodic downloading of data from the Internet, persisting multiple records in a database, performing file I/O, fetching a phone contacts list, and so on. Such long-running tasks can be implemented using services to provide a smooth user experience by letting the user interact with other activities, while long-running jobs are being processed in the background.
Content providers manage access to a central repository of data such as contacts. It provides you with a standard interface through which the other applications can access and manage the data repository.
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.
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 that is used to arrange (layout) other Views on the screen.
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 on the screen. 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:
It provides better separation of the visual design of an application from the processing logic
It 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 plugins for Eclipse and Xamarin Studio Android designer, allow you to view the user interface as you build it, without the need to compile and execute your application after each change
While most developers prefer the declarative method of View creation; in practice, some combination of programmatic and declarative methods is often required.
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 a 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.
The following screenshot depicts some of the basic Android widgets:

The application framework has a number of subclasses of ViewGroup
, each of which provides a unique and useful way of organizing content:

The preceding diagram depicts some of the common layout managers available in Android. Layout managers are the ViewGroup
classes that act as containers to host child views or layouts. Each of these standard layout managers provides a specific strategy to manage the size and position of its children. For example, the LinearLayout
class places its children either horizontally or vertically, one view adjacent to the other.
The following table lists the different types of layout managers available in Android:
For complex layout scenarios, Android allows layouts to be nested. Deeply nested layouts can have an impact on the performance and should be avoided if possible.
Tip
Downloading the example code
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.
For layouts that are driven by a dynamic data source, the application framework has a set of classes derived from AdapterView
:

The preceding diagram depicts two of the most common adapter layouts:
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 Windows Presentation Foundation (WPF) 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>
Care has been taken to align 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 class.
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.
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 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:
Start an activity with the option of receiving a result
Start or stop a service
Notify the component of conditions, such as low battery or time zone change
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
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.
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; } }
In this chapter, we have provided a concise and adequate introduction to the Android platform and the Android application's building blocks. We have also seen how the Android platform has evolved with rich features being added to each platform releases.
In the next chapter, we will turn our attention to Xamarin.Android and the facilities it provides to allow the Android development with .NET and C#.