Home Mobile Xamarin Mobile Application Development for Android, Second Edition

Xamarin Mobile Application Development for Android, Second Edition

books-svg-icon Book
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $43.99 $29.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    The Anatomy of an Android App
About this book
Publication date:
August 2015
Publisher
Packt
Pages
296
ISBN
9781785280375

 

Chapter 1. The Anatomy of an Android App

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


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.

Versions of Android

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:

Platform version

API level

Release date

Feature updates

5.1 (Lollipop)

22

03/09/2015

  • Stability and performance improvements over Lollipop.

  • Adds multiple SIM card support.

5.0 (Lollipop)

21

11/12/2014

  • Introduced new runtime ART that replaced Dalvik.

  • A complete UI overhaul with an introduction to material design.

  • Improved lock screen notification.

  • Updated the media API for better camera capture and media playback.

  • Added the project Volta to increase the battery life.

4.4W, 4.4W.1, 4.4W.2 (KitKat Wearables)

20

06/25/2014

  • Initial release for the Android Wear platform's smart watches.

  • Fork of same Android 4.4 KitKat code branch with added wearable extensions.

4.4.x (KitKat)

19

10/31/2013

  • The default interface is made white instead of blue.

  • Added wireless printing capability.

  • Support for translucent navigation and status bars.

  • Ability for apps to use immersive mode to allow navigation and status bars hidden while maintaining user interaction.

  • Action overflow menu buttons are always visible, even for the devices with the hardware Menu key.

  • New framework (property animation) for UI transitions.

  • Built-in screen recording feature.

  • Introduced Android Runtime (ART) as a new experimental runtime environment.

  • Other security enhancements and bug fixes.

4.3.x (Jelly Bean)

18

07/24/2013

  • Supports restricted access mode for new user profiles.

  • Introduced a platform support for Khronos OpenGL ES 3.0, providing better performance for 2D and 3D graphics rendering.

  • Bluetooth low energy support.

  • Optimized location and sensor capabilities, including hardware geo fencing optimizations.

  • Many security enhancements, performance enhancements, and bug fixes.

4.2, 4.2.2 (Jelly Bean)

17

11/13/2012

  • Improved the hardware-accelerated 2D renderer to make the animation smoother.

  • Introduced the interactive screensaver mode called Daydream.

  • Adds a presentation window and external display support.

  • Full native support for right-to-left (RTL) layouts.

  • Numerous bug fixes.

4.1, 4.1.x (Jelly Bean)

16

07/09/2012

  • Faster and smoother interface.

  • Bi-directional text and other language support.

  • Introduced expandable notification.

  • Added the new activity launcher animation via ActivityOptions.

  • Improved WebView to provide better HTML5 video viewing and canvas animation.

4.0.3, 4.0.4 (Ice Cream Sandwich)

15

12/16/2011

  • Bug fixes and stability improvements.

  • New APIs, including a social stream API in the Contacts provider.

  • Better camera performance.

  • Smoother screen rotation.

4.0, 4.0.1, 4.0.2 (Ice Cream Sandwich)

14

10/19/2011

  • Major interface overhaul with the new Roboto font family.

  • Unified the UI framework to work for phones, tablets, and more.

  • Lock screen improvements with the ability to access apps from lock screen.

  • Introduced the new voice input engine.

  • Improved media streaming capabilities.

  • Ability to shut down applications from the recent apps list with a swipe.

  • Hardware acceleration of the UI.

3.2.x (Honeycomb)

13

07/15/2011

  • Optimizations for a wider range of tablets.

  • Added a system-wide sync facility that made the SD card files accessible to apps from the system media store.

  • Bug fixes and other minor improvements.

3.1 (Honeycomb)

12

05/10/2011

  • Connectivity API for USB accessories.

  • Various UI framework updates.

  • Resizable home screen app widgets.

  • Support for an HTTP proxy for each connected Wi-Fi access point.

  • High-performance Wi-Fi lock, maintaining high-performance Wi-Fi connections when the device's screen is off.

  • Updated the animation framework class with ViewPropertyAnimator and animating background color.

3.0 (Honeycomb)

11

02/22/2011

  • Added a new user interface, which optimized tablets.

  • Introduced an action bar, giving access to contextual quick actions at the top of the screen.

  • Added the fragment, a self-contained container that can be embedded in an activity. It has its own life cycle callback and is used to design tablets.

  • Added the system-wide clipboard.

  • Improved the status bar notification to support more content-rich notifications.

  • Added new animation frameworks.

2.3.3, 2.3.7 (Gingerbread)

10

02/02/2011

  • Improvements and bug fixes.

2.3, 2.3.1, 2.3.2 (Gingerbread)

9

12/06/2010

  • Updated the user interface design for simplicity and speed.

  • Added support for Near Field Communication (NFC).

  • Support for extra-large screen sizes and resolutions.

  • Native support for more sensors, including gyroscopes and barometers.

  • Introduced the concurrent garbage collection for improved app responsiveness and smoother animation.

2.2.x (Froyo)

8

05/20/2010

  • Improved speed, memory, and performance optimizations.

  • Improved application speed using the JIT compilation.

  • Support for the Android Cloud to Device Messaging (C2DM) service.

  • Support for installing applications to the SD card memory.

  • USB tethering and Wi-Fi hotspot functionality.

  • Bug fixes and security patch updates.

2.1 (Eclair)

7

01/12/2010

  • Minor API changes and bug fixes.

2.0.1 (Eclair)

6

12/03/2009

  • Minor API changes and bug fixes.

2.0 (Donut)

5

10/26/2009

  • Updated camera features, including flash, digital zoom, white balance, color effect, and scene mode.

  • Optimized hardware speed and UI overhaul.

  • The MotionEvent class enhanced to track multi-touch events.

  • Expanded account sync, allowing users to add multiple accounts to a device.

1.6 (Donut)

4

09/15/2009

  • Multilingual speech synthesis engine added to convert a text to speech.

  • Updated support for CDMA/EVDO, 802.1x, VPNs technologies.

1.5 (Cupcake)

3

04/27/2009

  • Added third-party keyboard support with text prediction and user dictionary.

  • Video recording and playback in MPEG-4 and 3GP formats.

  • Added copy and paste features in the web browser.

  • Animated screen transitions.

  • Home screen widget support.

1.1

2

02/09/2009

  • First Android platform update.

  • Updated the Map application.

  • In-call screen timeout default is now longer when using the speakerphone.

  • Adds support for saving attachments from MMS.

  • Adds support for marquee in layouts.

  • Various bug fixes.

1.0

1

09/23/2008

  • First commercial version of the Android platform.

  • Included apps such as Android Market, Gmail, Camera, Calendar, Contacts, Google Talk, Map, Media Player, Picture, Settings, and Browser.

  • Wi-Fi and Bluetooth support.

  • Instant messaging, text messaging, and MMS support.

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:

The Linux kernel

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.

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

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


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.

The application layer

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.

 

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

Summary


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

Xamarin Mobile Application Development for Android, Second Edition
Unlock this book and the full library FREE for 7 days
Start now