The Lifecycle of an Android Activity

Android applications can be multi-process, and the Android operating system allows multiple applications to run concurrently, provided memory and processing power is available. Applications can have background processes, and applications can be interrupted and paused when events such as phone calls occur. There can be only one active application visible to the user at a time specifically, a single application Activity is in the foreground at any given time. The Android operating system keeps...

Performing Application Tasks with Activities

The Android Activity class (android.app.Activity) is core to any Android application. Much of the time, you define and implement an Activity class for each screen in your application. For example, a simple game application might have the following five Activities, as shown in Figure 4.1 A Startup or Splash screen This activity serves as the primary entry point to the application. It displays the application name and version information and transitions to the Main menu after a short interval. A...

Warning

Because the Activity class is derived from the Context class, you can sometimes use this instead of retrieving the application Context explicitly. However, don't be tempted to just use your Activity Context in all cases because doing so can lead to memory leaks. You can find a great article on this topic at 01 avoiding-memory-leaks.html.

Accessing Other Application Functionality Using Context

The application Context provides access to a number of other top-level application features. Here are a few more things you can do with the application Context Retrieve assets packaged with the application Request a system service (for example, location service) Manage private application files, directories, and databases Inspect and enforce application permissions The first item on this list launching Activity instances is perhaps the most common reason you use the application Context.

Retrieving Application Resources

You can retrieve application resources using the getResources() method of the application Context.The most straightforward way to retrieve a resource is by using its resource identifier, a unique number automatically generated within the R.java class.The following example retrieves a String instance from the application resources by its resource ID String greeting We talk more about application resources in Chapter 6,Managing Application Resources.

Proprietary Mobile Platforms

It came as no surprise that users wanted more they will always want more. Writing robust applications with WAP, such as graphic-intensive video games, was nearly impossible.The 18-year-old to 25-year-old sweet-spot demographic the kids with the disposable income most likely to personalize their phones with wallpapers and ringtones looked at their portable gaming systems and asked for a device that was both a phone and a gaming device or a phone and a music player.They argued that if devices...

The Android Platform

Android is an operating system and a software platform upon which applications are de-veloped.A core set of applications for everyday tasks, such as web browsing and email, are included on Android handsets. As a product of the OHA's vision for a robust and open source development environment for wireless,Android is an emerging mobile development platform.The platform was designed for the sole purpose ofencouraging a free and open market that all mobile applications phone users might want to...

Reasonable Learning Curve for Developers

Android applications are written in a well-respected programming language Java. The Android application framework includes traditional programming constructs, such as threads and processes and specially designed data structures to encapsulate objects commonly used in mobile applications. Developers can rely on familiar class libraries, such as java.net and java.text. Specialty libraries for tasks such as graphics and database management are implemented using well-defined open standards such as...

Configuring the Android Manifest File

The Android application manifest file is a specially formatted XML file that must accompany each Android application. This file contains important information about the application's identity. Here you define the application's name and version information and what application components the application relies upon, what permissions the application requires to run, and other application configuration information. The Android manifest file is named AndroidManifest.xml and must be included at the...

Registering Activities and Other Application Components

Each Activity within the application must be defined within the Android manifest file with an < activity> tag. For example, the following XML excerpt defines an Activity class called AudioActivity < activity android name AudioActivity > This Activity must be defined as a class within the com.androidbook.multimedia package.That is, the package specified in the < manifest> element of the Android manifest file.You can also enforce scope of the activity class by using the dot as a...

Problems with the Android Software Development

Because the Android SDK is constantly under active development, you might come across problems with the SDK. If you think you've found a problem, you can find a list of open issues and their status at the Android project Issue Tracker website.You can also submit new issues for review. The Issue Tracker website for the Android open source project is http code.google. com p android issues list. For more information about logging your own bugs or defects to be considered by the Android platform...

Configuring the Location of the Emulator

After you have created a new AVD with the Google APIs support, you need to shut down the emulator you've been running. Then debug the My First Android App application again, this time choosing the new AVD. The emulator does not have location sensors, so the first thing you need to do is seed your emulator with GPS coordinates.To do this, launch your emulator in debug mode with an AVD supporting the Google Maps add-ins and follow these steps In the Emulator 1. Press the Home key to return to the...

Reading the Android SDK Documentation

A local copy of the Android documentation is provided in the docs subfolder on disk (as shown in Figure 2.3). The documentation is now divided into seven main sections The Home tab is your general starting point within the Android documentation. Here you find developer announcements and important links to the latest hot topics in Android development. The SDK tab provides information about the different Android SDK versions available, as well as information about the Android Native Development...

Configuring Other Intent Filters

The Android operating system uses Intent filters to resolve implicit intents.That is, Intents that do not specify the Activity or Component they want launched. Intent filters can be applied to Activities, Services, and BroadcastReceivers.The filter declares that this component is open to receiving any Intent sent to the Android operating system that matches its criteria. Intent filters are defined using the < intent-filter> tag and must contain at least one < action> tag but can also...

Designating a Primary Entry Point Activity for Your Application Using an Intent Filter

An Activity class can be designated as the primary entry point by configuring an intent filter using the Android manifest tag < intent-filter> in the application's AndroidManifest.xml file with the MAIN action type and the LAUNCHER category. Registering Activities and Other Application Components 93 The following tag of XML configures the Activity class called MultimediaMenuActivity as the primary launching point of the application < activity < intent-filter> < action MAIN > <...

Adding Logging Support to Your Android Application

Before you start diving into the various features of the Android SDK, you should familiarize yourself with logging, a valuable resource for debugging and learning Android. Android logging features are in the Log class of the android.util package. Some helpful methods in the android.util.Log class are shown in Table 3.2. To add logging support to MyFirstAndroidApp, edit the file MyFirstAndroidApp.java. First, you must add the appropriate import statement for the Log class To save time in...

Versioning Your Application

Versioning your application appropriately is vital to maintaining your application in the field. Intelligent versioning can help reduce confusion and make product support and upgrades simpler. There are two different version attributes defined within the < manifest> tag the version name and the version code. The version name (android versionName) is a user-friendly, developer-defined version attribute. This information is displayed to users when they manage applications on their devices and...

Targeting Different Device Configurations and Languages 523

Maximizing Application Compatibility 523 Designing User Interfaces for Compatibility 525 Supporting Specific Screen Types 526 Working with Nine-Patch Stretchable Graphics 526 Using the Working Square Principle 528 Providing Alternative Application Resources 531 Working with Alternative Resource Qualifiers 531 Providing Resources for Different Orientations 537 Using Alternative Resources Programmatically 538 Organizing Application Resources Efficiently 538 Internationalizing Applications 539...

The Mobile Software Development Process 551

An Overview of the Mobile Development Process 551 Choosing a Software Methodology 552 Understanding the Dangers of Waterfall Approaches 552 Understanding the Value of Iteration 553 Gathering Application Requirements 553 Determining Project Requirements 553 Developing Use Cases for Mobile Applications 555 Incorporating Third-Party Requirements 555 Managing a Device Database 555 Assessing Project Risks 558 Identifying Target Devices 558 Acquiring Target Devices 560 Determining Feasibility of...

Understanding the Android SDK License Agreement

Before you can download the Android SDK, you must review and agree to the Android SDK License Agreement. This agreement is a contract between you (the developer) and Google (copyright holder of the Android SDK). Even if someone at your company has agreed to the Licensing Agreement on your behalf, it is important for you, the developer, to be aware of a few important points 1. Rights granted Google (as the copyright holder of Android) grants you a limited, worldwide, royalty-free,...

Familiar Language Familiar Development Environments

Developers have several choices when it comes to integrated development environments (IDEs). Many developers choose the popular and freely available Eclipse IDE to design and develop Android applications. Eclipse is the most popular IDE for Android development, and there is an Android plug-in available for facilitating Android development. Android applications can be developed on the following operating systems Windows XP (32-bit) or Vista (32-bit or 64-bit) Mac OS X 10.5.8 or later (x86 only)...

Designing and Developing Bulletproof Android Applications 571

Best Practices in Designing Bulletproof Mobile Applications 571 Meeting Mobile Users' Demands 572 Designing User Interfaces for Mobile Devices 572 Designing Stable and Responsive Mobile Applications 573 Designing Secure Mobile Applications 574 Designing Mobile Applications for Maximum Profit 575 Leveraging Third-Party Standards for Android Application Design 576 Designing Mobile Applications for Ease of Maintenance and Upgrades 576 Leveraging Android Tools for Application Design 578 Avoiding...

Understanding the Anatomy of an Android Application

Classical computer science classes often define a program in terms of functionality and data, and Android applications are no different. They perform tasks, display information to the screen, and act upon data from a variety of sources. Developing Android applications for mobile devices with limited resources requires a thorough understanding of the application lifecycle. Android also uses its own terminology for these application building blocks terms such as Context, Activity, and...

Content Providers Developing Android Applications

When users have Android handsets, they need those killer apps, right Google has led the pack, developing Android applications, many of which, such as the email client and web browser, are core features of the platform. OHA members are also working on Android application integration. eBay, for example, is working on integration with its online auctions. The first ADC received 1,788 submissions, with the second ADC being voted upon by 26,000 Android users to pick a final 200 applications that...

Android Application Framework

The Android application framework provides everything necessary to implement your average application.The Android application lifecycle involves the following key components Activities are functions the application performs. Groups of views define the application's layout. Intents inform the system about an application's plans. Services allow for background processing without user interaction. Notifications alert the user when something interesting happens. Android applications can interact...

Mastering Important Android Terminology

This chapter introduces you to the terminology used in Android application development and provides you with a more thorough understanding of how Android applications function and interact with one another. Some of the important terms covered in this chapter are Context The context is the central command center for an Android application. All application-specific functionality can be accessed through the context. Activity An Android application is a collection of tasks, each of which is called...

Core Files and Directories of the Android Application

Every Android application has a set of core files that are created and are used to define the functionality of the application (see Table 3.1).The following files are created by default with a new Android application. Figure 3.8 Configuring My First Android App using the Android Project Wizard. Figure 3.8 Configuring My First Android App using the Android Project Wizard. There are a number of other files saved on disk as part of the Eclipse project in the workspace. However, the files included...

Key Questions Answered in This Book

This book answers the following questions 1. What is Android How do the SDK versions differ 2. How is Android different from other mobile technologies, and how can developers take advantage of these differences 3. How do developers use the Eclipse Development Environment for Java to develop and debug Android applications on the emulator and handsets 4. How are Android applications structured 5. How do developers design robust user interfaces for mobile specifically, for Android 6. What...

Tip

When users install the application, they are informed what permissions the application requires to run and must approve these permissions. Request only the permissions your application requires. The following XML excerpt for the preceding Android manifest file defines a permission using the lt uses-permission gt tag to gain access to the built-in camera A complete list of the permissions can be found in the android.Manifest.permission class.Your application manifest should include only the...

Editing the Manifest File Manually

The Android manifest file is a specially formatted XML file.You can edit the XML manually by clicking on the AndroidManifest.xml tab. Android manifest files generally include a single lt manifest gt tag with a single lt application gt tag.The following is a sample AndroidManifest.xml file for an application called Multimedia lt xml version 1.0 encoding utf-8 gt lt manifest android versionCode 1 android versionName 1.0 gt lt application android icon drawable icon lt activity lt intent-filter gt...

Working with External Libraries

You can register any shared libraries your application links to within the Android manifest file. By default, every application is linked to the standard Android packages such as android.app and is aware of its own package. However, if your application links to additional packages, they must be registered within the lt application gt tag of the Android manifest file using the lt uses-library gt tag. For example lt uses-library gt This feature is often used for linking to optional Google APIs....

Receiving and Broadcasting Intents

Intents serve yet another purpose.You can broadcast an Intent object via a call to broadcastlntent to the Android system, and any application interested can receive that broadcast called a BroadcastReceiver .Your application might do both sending of and listening for Intent objects.These types of Intent objects are generally used to inform the greater system that something interesting has happened and use special Intent Action types. For example, the Intent action action_battery_low broadcasts...

Android Hierarchy Viewer

The Android Hierarchy Viewer see Figure 2.8 , a visual tool that illustrates layout component relationships, helps developers design and debug user interfaces. Developers can use this tool to inspect the View properties and develop pixel-perfect layouts. For more information about user interface design and the Hierarchy Viewer, see Chapter 8,Designing User Interfaces with Layouts. Figure 2.8 Screenshot of the Android Hierarchy Viewer in action. Figure 2.8 Screenshot of the Android Hierarchy...

Specifying the Target SDK Version

You should always specify the targetSdkVersion attribute for your application.This value represents the Android SDK version your application was built for and tested against. For example, if your application was built using the APIs that are backward-compatible to Android 1.6 API Level 4 , but targeted and tested using Android 2.2 SDK API Level 8 , then you would want to specify the targetSdkVersion attribute as 8.Therefore, add the following to your Android manifest file within the lt manifest...

Summary

Each Android application has a specially formatted XML file called AndroidManifest.xml.This file describes the application's identity in great detail. Some information you must define within the Android manifest file includes the application's name and version information, what application components it contains, which device configurations it requires, and what permissions it needs to run. The Android manifest file is used by the Android operating system to install, upgrade, and run the...

Wireless Application Protocol WAP

As it turned out, allowing direct phone access to the Internet didn't scale well for mobile. By this time, professional websites were full color and chock full of text, images, and other sorts of media.These sites relied on JavaScript, Flash, and other technologies to enhance the user experience, and they were often designed with a target resolution of 800x600 pixels and higher. When the first clamshell phone, the Motorola StarTAC, was released in 1996, it merely had an LCD 10-digit segmented...

Using Activity Callbacks to Manage Application State and Resources

Activity Life Cycle Android

Different important state changes within the Activity lifecycle are punctuated by a series of important method callbacks.These callbacks are shown in Figure 4.3. Here are the method stubs for the most important callbacks of the Activity class public class MyActivity extends Activity protected void onCreate Bundle savedlnstanceState protected void onStart protected void onRestart protected void onResume protected void onPause protected void onStop protected void onDestroy protected void onResume...

Exploring Other Manifest File Settings

We have now covered the basics of the Android manifest file, but there are many other settings configurable within the Android manifest file using different tag blocks, not to mention attributes within each tag we already discussed. Some other features you can configure within the Android manifest file include Setting application-wide themes as lt application gt tag attributes Configuring instrumentation using the lt instrumentation gt tag Aliasing activities using the lt activity-alias gt tag...

Androids Underlying Architecture

The Android platform is designed to be more fault-tolerant than many of its predecessors. The handset runs a Linux operating system upon which Android applications are executed in a secure fashion. Each Android application runs in its own virtual machine see Figure 1.8 . Android applications are managed code therefore, they are much less likely to cause the phone to crash, leading to fewer instances of device corruption also called bricking the phone, or rendering it useless . The Linux 2.6...

Specifying Required Device Features

Not all Android devices support every Android feature. Put another way There are a number of APIs and related hardware that Android devices may optionally include. For example, not all Android devices have multi-touch ability or a camera flash. The lt uses-feature gt tag can be used to specify which Android features the application requires to run properly. These settings are for informational purposes only the Android operating system does not enforce these settings, but publication channels...

Setting Simple Resource Values Using Eclipse

Developers can define resource types by editing resource XML files manually and using the aapt to compile them and generate the R.java file or by using Eclipse with the Android plug-in, which includes some very handy resource editors. To illustrate how to set resources using the Eclipse plug-in, let's look at an example. Create a new Android project and navigate to the res values strings.xml file in Eclipse and double-click the file to edit it.Your strings.xml resource file opens in the right...

Dalvik Debug Monitor Server DDMS

The Dalvik Debug Monitor Server DDMS is a command-line tool that has also been integrated into Eclipse as a perspective see Figure 2.7 .This tool provides you with direct access to the device whether it's the emulator virtual device or the physical device.You use DDMS to view and manage processes and threads running on the device, view heap data, attach to processes to debug, and a variety of other tasks. Figure 2.7 Using DDMS integrated into an Eclipse perspective. Figure 2.7 Using DDMS...

Finding the Last Known Location

To add location support to MyFirstAndroidApp, edit the file MyFirstAndroidApp.java. First, you must add the appropriate import statements import android.location.Location import android.location.LocationManager Now, create a new method called getLocation in your class and make a call to this method in your onCreate method.The getLocation method gets the last known location on the phone and logs it as an informational message. If the operation fails for some reason, the method logs an error. The...

Stopping Saving and Releasing Activity Data in onPause

When another Activity moves to the top ofthe activity stack, the current Activity is informed that it is being pushed down the activity stack by way of the onPause method. Here, the Activity should stop any audio, video, and animations it started in the onResume method.This is also where you must deactivate resources such as database Cursor objects if you have opted to manage them manually, as opposed to having them managed automatically. Android provides a number of helper utilities for...

Creating an Android Virtual Device AVD for Your Snake Project

The next step is to create an AVD that describes what type of device you want to emulate when running the Snake application.This AVD profile describes what type of device you want the emulator to simulate, including which Android platform to support.You can specify different screen sizes and orientations, and you can specify whether the emulator has an SD card and, if it does, what capacity the card is. I -I . I I 1 j Cwa Figure 3.2 The Snake project details. For the purposes of this example,...

Adding Some Media Support to Your Application

Next, let's add some pizzazz to MyFirstAndroidApp by having the application play an MP3 music file.Android media player features are found in the MediaPlayer class of the android.media package. You can create MediaPlayer objects from existing application resources or by specifying a target file using a Uniform Resource Identifier URI . For simplicity, we begin by accessing an MP3 using the Uri class from the android.net package. Some methods in the android.media.MediaPlayer and android.net.Uri...

Debugging Your Android Application in the Emulator

Before we go any further, you need to become familiar with debugging in the emulator. To illustrate some useful debugging tools, let's manufacture an error in the My First Android Application. In your project, edit the file MyFirstAndroidApp.java and create a new method called forceError in your class and make a call to this method in your onCreate method. The forceError method forces a new unhandled error in your application. The forceError method should look something like this public void...