Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
Xamarin Mobile Application Development for Android, Second Edition
Xamarin Mobile Application Development for Android, Second Edition

Xamarin Mobile Application Development for Android, Second Edition: Develop, test, and deliver fully-featured Android applications using Xamarin

eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Xamarin Mobile Application Development for Android, Second Edition

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:

Versions of Android

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:

The Android runtime

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

Fragments

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:

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:

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

Common layouts

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:

Adapter layouts

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

Left arrow icon Right arrow icon

Description

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 learn the fundamentals of Android app development using C# and Xamarin.Android. It will lead you through building an Android app step-by-step with steadily increasing complexity. Beginning with an overview of the Android and Xamarin platforms to provide you with a solid understanding of the underlying platform, we gradually walk through building and testing a Points of Interest Android app using C# and the Xamarin.Android product. You will learn to create ListView and add detail view to your Android application. You will handle application behaviors on orientation changes, before learning the different techniques to manage resources and layouts to support multiple screen sizes. You will then access a SQLite database in a cross-platform way and add location features to your application. Finally, you will add camera integration to your application and deploy your app to the various Android app stores.

Who is this book for?

If you are a C# developer who wants to develop Android apps and enhance your existing skill set, then this book is ideal for you. Good working knowledge of C#, .NET, and object-oriented software development is assumed.

What you will learn

  • Build a multiview, orientationaware Android application with navigation
  • Lay out content using the LinearLayout, RelativeLayout, and TableLayout layout managers
  • Use a ListView (AdapterView) and Adapter to build a view that is populated from server data
  • Consume REST web service to perform GET, UPDATE, DELETE operation
  • Use Android SQLite for data persistence and caching
  • Capture the current location of a device, determine the street address, and integrate with the map app
  • Test, debug, and deploy an Android app

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 24, 2015
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781785280634
Vendor :
Microsoft
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 24, 2015
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781785280634
Vendor :
Microsoft
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 102.97
Mastering Xamarin.Forms
€24.99
Xamarin Mobile Application Development for Android, Second Edition
€41.99
Cross-platform UI Development with Xamarin.Forms
€35.99
Total 102.97 Stars icon
Banner background image

Table of Contents

12 Chapters
1. The Anatomy of an Android App Chevron down icon Chevron up icon
2. The Xamarin.Android Architecture Chevron down icon Chevron up icon
3. Creating the Points Of Interest App Chevron down icon Chevron up icon
4. Adding a List View Chevron down icon Chevron up icon
5. Adding a Details View Chevron down icon Chevron up icon
6. Making Your App Orientation-aware Chevron down icon Chevron up icon
7. Designing for Multiple Screen Sizes Chevron down icon Chevron up icon
8. Creating Data Storage Mechanisms Chevron down icon Chevron up icon
9. Making POIApp Location Aware Chevron down icon Chevron up icon
10. Adding the Camera App Integration Chevron down icon Chevron up icon
11. Publishing an App to the App Store Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.7
(3 Ratings)
5 star 0%
4 star 33.3%
3 star 0%
2 star 66.7%
1 star 0%
Pietro F. Maggi Sep 13, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Nice book to get C# developer quickly up to speed with Xamarin for Android Development.The first two chapters are a very quick introduction to the basic Android and Xamarin architecture concepts, especially the first chapter on Android is very skinny given the size of the topic, but ehi, this is Xamarin book!The rest of the book, from chapter three to eleven, drive you on the process to build a Point of Interest application from the start to the publishing process.This kind of approach is sometime risky, largely depending on the application the author choose to implement. In this case the application, even if a basic one, allows to touch a lot of the point o a real world application, from Activity/Fragment lifecycle management to data persistence and Webservice integration.Overall I liked the book and I've found some good insight in it. I gave only four star and not five because the approach to write the book around a single application does not allows to touch all the topics of the Xamarin for Android platform. However, if you're looking for a beginner introduction to Xamarin for Android, this book is a really good choice.
Amazon Verified review Amazon
Trenton L. Aug 17, 2017
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
My Senior Design Project was developing an app using Xamarin mobile development. This book did NOT help
Amazon Verified review Amazon
Anthony Scarpelli Sep 16, 2020
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
This book is almost usable, but it is way out of date already.Xamarin Studio IDE no longer exists which is what you would use with this book.You can create the application in Visual Studio 2019 if you try hard enough, but you need to know that the application created in Visual Studio is not quite the same as is described in the book.I was able to get through the building of the app up to a certain point, then the differences will sock you in the head and you just can't go further unless you are more experienced.Too bad.Can't recommend it until they update it again for the current time frame.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.