Book Image

Xamarin Mobile Application Development for Android, Second Edition

Book Image

Xamarin Mobile Application Development for Android, Second Edition

Overview of this book

Table of Contents (18 chapters)
Xamarin Mobile Application Development for Android Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

The building blocks of the Android application


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.

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 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.

The application manifest

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

Activities

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.

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 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

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 the 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. The following table describes the different event callbacks and typically, the processing done in the application during each callback:

Event

Called

Typical processing

onCreate

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

  • This creates Views

  • This initializes variables

  • This allocates long-lived resources

onStart

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

  • This allocates resources

onResume

Before an activity is ready to start interacting with a user and immediately after the onStart callback

  • This initializes UI widgets for viewing

  • This starts animations or videos

  • This starts listening for GPS updates

onPause

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

  • This commits unsaved updates

  • This pauses animations or videos

  • This stops listening for GPS updates

onStop

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

  • This releases resources

onRestart

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

  • This allocates resources

onDestroy

Before the activity is destroyed

  • This cleans up resources that may have been allocated by an activity

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.

Fragments

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.

The fragment life cycle

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 the fragment tag, and while the content view of the activity is being inflated (typically, when setContentView() is called on an activity). This method passes AttributeSet that holds all the fragment attributes passed from the fragment 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 after onAttach and before onCreateView; 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, and bundle. The LayoutInflater argument can be used to inflate any layout for a fragment. A bundle 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 the findViewById() method and make any changes before it is visible to the user.

  • onStart: This method is tied to the activity onStart() 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 activity onPause() callback and is called when the fragment is taken out of the foreground.

  • onStop: This method is tied to the activity onStop() callback and called when the fragment is not visible.

  • onDestroyView: This method tells the fragment that the view created from onCreateView() is now detached from the fragment. This callback is called after onStop() and before the onDestroy() method.

  • onDestroy: This method is called when the fragment is no longer in use. This is called after onStop() and before onDetach().

  • onDetach: This method is called after onDestroy(), and when the fragment is no longer attached to an activity.

Services

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

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

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 that 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 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.

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 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:

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 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:

Layout

Description

Scenario

Linear layout

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

Use this when widget positions flow horizontally or vertically.

Relative layout

This organizes child objects relative to each other or to the parent.

Use this 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

This organizes its children into rows and columns.

Use this when widget positions would naturally fit into rows and columns. This is great when multiple columns of entry and labels are needed.

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.

Adapter layouts

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:

  • ListView: This organizes content from the data source into a scrolling single column list

  • GridView: This 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 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>

Element and attribute names

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.

The View and layout identifiers

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:

  • 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

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.

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;
  }
}