[Android Software Development] michael.the.don:
[Ultimate Guide][Part 3-1/09/2011]Android App Development - From Scrap

PART III

Creating Applications and Activities

Before you start writing Android applications, it’s important to understand how they’re constructed and have an understanding of the Android application life cycle. In this chapter, you’ll be introduced to the loosely coupled components that make up Android applications (and how they’re bound together using the Android manifest).

Android applications consist of loosely coupled components, bound using a project manifest that describes each component and how they interact. There are six components that provide the building blocks for your applications:

❑ Activities Your application’s presentation layer. Every screen in your application will be an extension of the Activity class. Activities use Views to form graphical user interfaces that display information and respond to user actions. In terms of desktop development, an Activity is equivalent to a Form.

❑ Services The invisible workers of your application. Service components run invisibly, updating your data sources and visible Activities and triggering Notifications. They’re used to perform regular processing that needs to continue even when your application’s Activities aren’t active or visible.

❑ Content Providers A shareable data store. Content Providers are used to manage and share application databases. Content Providers are the preferred way of sharing data across application boundaries. This means that you can configure your own Content Providers to permit access from other applications and use Content Providers exposed by others to access their stored data. Android devices include several native Content Providers that expose useful databases like contact information.

❑ Intents A simple message-passing framework. Using Intents, you can broadcast messages system- wide or to a target Activity or Service, stating your intention to have an action performed. The system will then determine the target(s) that will perform any actions as appropriate.

❑ Broadcast Receivers Intent broadcast consumers. By creating and registering a Broadcast Receiver, your application can listen for broadcast Intents that match specific filter criteria. Broadcast Receivers will automatically start your application to respond to an incoming Intent, making them ideal for event-driven applications.

❑ Notifications A user notification framework. Notifications let you signal users without stealing focus or interrupting their current Activities. They’re the preferred technique for getting a user’s attention from within a Service or Broadcast Receiver. For example, when a device receives a text message or an incoming call, it alerts you by flashing lights, making sounds, displaying

icons, or showing dialog messages. You can trigger these same events from your own applications using Notifications

Introducing the Application Manifest

Each Android project includes a manifest file, AndroidManifest.xml, stored in the root of the project hierarchy. The manifest lets you define the structure and metadata of your application and its components. It includes nodes for each of the components (Activities, Services, Content Providers, and Broadcast Receivers) that make up your application and, using Intent Filters and Permissions, determines how they interact with each other and other applications.

It also offers attributes to specify application metadata (like its icon or theme), and additional top-level nodes can be used for security settings. The manifest is made up of a root manifest tag with a package attribute set to the project’s package.

It usually includes an xmlns:android attribute that supplies several system attributes used within the

file.

A typical manifest node is shown in the XML snippet below:

<manifest xmlns:android=http://schemas.android.com/apk/res/android

package=”com.my name.myapp”>

[ ... manifest nodes ... ]

</manifest>

The manifest tag includes nodes that define the application components, security settings, and test classes that make up your application. The following list gives a summary of the available manifest node tags, and an XML snippet demonstrating how each one is used:

❑ application A manifest can contain only one application node. It uses attributes to specify the metadata for your application (including its title, icon, and theme). It also acts as a container that includes the Activity, Service, Content Provider, and Broadcast Receiver tags used to specify the application components.

<application android:icon=”@drawable/icon”

android:theme=”@style/my_theme”>

[ ... application nodes ... ]

</application>

❑ activity An activity tag is required for every Activity displayed by your application, using the android:name attribute to specify the class name. This must include the main launch Activity and any other screen or dialogs that can be displayed. Trying to start an Activity that’s not defined in the manifest will throw a runtime exception. Each Activity node supports intent-filter child tags that specify which Intents launch the Activity.

<activity android:name=”.MyActivity” android:label=”@string/name”>

<intent-filter>

<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />

</intent-filter>

</activity>

❑ service As with the activity tag, create a new service tag for each Service class used in your application. Service tags also

support intent-filter child tags to allow late runtime binding.

<service android:enabled=”true” android:name=”.MyService”></service>

❑ provider Provider tags are used for each of your application’s Content Providers. Content Providers are used to manage database access and sharing within and between applications.

<provider android:permission=”com.paad.MY_PERMISSION”

android:name=”.MyContentProvider”

android:enabled=”true”

android:authorities=”com.paad.myapp.MyContentProvider”>

</provider>

❑ receiver By adding a receiver tag, you can register a Broadcast Receiver without having to launch your application fi rst. As Broadcast Receivers are like global event listeners that, once registered, will execute whenever a matching Intent is broadcast by an application. By registering a Broadcast Receiver in the manifest, you can make this process entirely autonomous. If a matching Intent is broadcast, your application will be started automatically and the registered Broadcast Receiver

will be run.

<receiver android:enabled=”true”

android:label=”My Broadcast Receiver”

android:name=”.MyBroadcastReceiver”>

</receiver>

❑ uses-permission As part of the security model, uses-permission tags declare the permissions you’ve determined that your application needs for it to operate properly. The permissions you include will be presented to the user, to grant or deny, during installation. Permissions are required for many of the native Android services, particularly those with a cost or security implication (such as dialing, receiving SMS, or using the location-based services). As shown in the item below, third-party applications, including your own, can also specify permissions before providing access to shared application components.

<uses-permission android:name=”android.permission.ACCESS_LOCATION”>

</uses-permission>

❑ permission Before you can restrict access to an application component, you need to define a permission in the manifest. Use the permission tag to create these permission definitions. Application components can then require them by adding the android:permission attribute. Other applications will then need to include a uses-permission tag in their manifests (and

have it granted) before they can use these protected components. Within the permission tag, you can specify the level of access the permission will permit (normal, dangerous, signature, signatureOrSystem), a label, and an external resource containing the description that explain the risks of granting this permission.

<permission android:name=”com.paad.ALERT_DEVICE”

android:protectionLevel=”dangerous”

android:label=”Alert”

android:description=”@string/detonate_description”>

</permission>

❑ instrumentation Instrumentation classes provide a framework for running tests on your Activities and Services at run time. They provide hooks to monitor your application and its interaction with the system resources. Create a new node for each of the test classes you’ve created for your application.

<instrumentation android:label=”My Test”

android:name=”.MyTestClass”

android:targetPackage=”com.paad.aPackage”>

</instrumentation>

The ADT New Project Wizard automatically creates a new manifest file when it creates a new project. You’ll return to the manifest as each of the application components is introduced.

Using the Manifest Editor

The ADT plug-in includes a visual Manifest Editor to manage your manifest, rather than you having to manipulate the underlying XML directly. To use the Manifest Editor in Eclipse, right-click the AndroidManifest.xml fi le in your project folder, and select Open With ➪ Android Manifest Editor. This presents the Android Manifest Overview screen. This gives you a high-level view of your application structure and provides shortcut links to the Application, Permissions, Instrumentation, and raw XML screens. Each of the next three tabs contains a visual interface for managing the application, security, and instrumentation (testing) settings, while the last tag (using the manifest’s filename) gives access to the raw XML.

Application Life Cycle

Android applications have no control over their own life cycles. Instead, application components must listen for changes in the application state and react accordingly, taking particular care to be prepared for untimely termination. As mentioned before, by default, each Android application is run in its own process that’s running a separate instance of Dalvik. Memory and process management of each application is handled exclusively by the run time. Android aggressively manages its resources, doing whatever it takes to ensure that the device remains responsive. This means that processes will be killed, without warning if necessary, to free resources for higher-priority application, generally those that are interacting directly with the user at the time.

Understanding Application Priority and Process States

The order in which processes are killed to reclaim resources is determined by the priority of the hosted applications. An application’s priority is equal to its highest-priority component.

The following list details each of the application states, explaining how the state is determined by the application components comprising it:

❑ Active Processes Active (foreground) processes are those hosting applications with components currently interacting with the user. These are the processes Android is trying to keep responsive by reclaiming resources. There are generally very few of these processes, and they will be killed only as a last resort.

❑ Visible Processes Visible, but inactive processes are those hosting “visible” Activities. As the name suggests, visible Activities are visible, but they aren’t in the foreground or responding to user events. This happens when an Activity is only partially obscured (by a non-full-screen or transparent Activity). There are generally very few visible processes, and they’ll only be killed in extreme circumstances to allow active processes to continue.

❑ Started Service Processes Processes hosting Services that have been started. Services support ongoing processing that should continue without a visible interface. Because Services don’t interact directly with the user, they receive a slightly lower priority than visible Activities. They are still considered to be foreground processes and won’t be killed unless resources are needed

for active or visible processes.

❑ Background Processes Processes hosting Activities that aren’t visible and that don’t have any Services that have been started are considered background processes. There will generally be a large number of background processes that Android will kill using a last-seen-first-killed pattern to obtain resources for foreground processes.

❑ Empty Processes To improve overall system performance, Android often retains applications in memory after they have reached the end of their lifetimes. Android maintains this cache to improve the start-up time of applications when they’re re-launched. These processes are routinely killed as required.

Creating Resources

Application resources are stored under the res/ folder of your project hierarchy. In this folder, each of the available resource types can have a subfolder containing its resources. If you start a project using the ADT wizard, it will create a res folder that contains subfolders for the values, drawable, and layout resources that contain the default layout, application icon, and string

resource definitions, respectively. There are seven primary resource types that have different folders: simple values, drawables, layouts, animations, XML, styles, and raw resources. When your application is built, these resources will be

compiled as efficiently as possible and included in your application package.

This process also creates an R class file that contains references to each of the resources you include in your project. This lets you reference the resources in your code, with the advantage of design time syntax checking.

Creating Simple Values

Supported simple values include strings, colors, dimensions, and string or integer arrays. All simple values are stored within XML fi les in the res/values folder. Within each XML fi le, you indicate the type of value being stored using tags as shown in the sample XML file below:

<?xml version=”1.0” encoding=”utf-8”?>

<resources>

<string name=”app_name”>To Do List</string>

<color name=”app_background”>#FF0000FF</color>

<dimen name=”default_border”>5px</dimen>

<array name=”string_array”>

<item>Item 1</item>

<item>Item 2</item>

<item>Item 3</item>

</array>

<array name=”integer_array”>

<item>3</item>

<item>2</item>

<item>1</item>

</array>

</resources>

Strings

Externalizing your strings helps maintain consistency within your application and makes it much easier to create localized versions. String resources are specified using the string tag as shown in the following XML snippet:

<string name=”stop_message”>Stop.</string>

Android supports simple text styling, so you can use the HTML tags <b>, <i>, and <u> to apply bold, italics, or underlining to parts of your text strings as shown in the example below:

<string name=”stop_message”><b>Stop.</b></string>

You can use resource strings as input parameters for the String.format method. However, String.format does not support the text styling described above. To apply styling to a format string, you have to escape the HTML tags when creating your resource, as shown below:

<string name=”stop_message”><b>Stop</b>. %1$s</string>

Within your code, use the Html.fromHtml method to convert this back into a styled character sequence:

String rString = getString(R.string.stop_message);

String fString = String.format(rString, “Collaborate and listen.”);

CharSequence styledString = Html.fromHtml(fString);

Colors

Use the color tag to define a new color resource. Specify the color value using a # symbol followed by the (optional) alpha channel, then the red, green, and blue values using one or two hexadecimal numbers with any of the following notations:

❑ #RGB

❑ #RRGGBB

❑ #ARGB

❑ #ARRGGBB

Dimensions

Dimensions are most commonly referenced within style and layout resources. They’re useful for creating layout constants such as borders and font heights. To specify a dimension resource, use the dimen tag, specifying the dimension value, followed by an

identifi er describing the scale of your dimension:

❑ px Screen pixels

❑ in Physical inches

❑ pt Physical points

❑ mm Physical millimeters

❑ dp Density-independent pixels relative to a 160-dpi screen

❑ sp Scale-independent pixels

Styles and Themes

Style resources let your applications maintain a consistent look and feel by specifying the attribute values used by Views. The most common use of themes and styles is to store the colors and fonts for an application. To create a style, use a style tag that includes a name attribute, and contains one or more item tags.

Each item tag should include a name attribute used to specify the attribute (such as font size or color) being defened. The tag itself should then contain the value, as shown in the raw code below:

<?xml version=”1.0” encoding=”utf-8”?>

<resources>

<style name=”StyleName”>

<item name=”attributeName”>value</item>

</style>

</resources>

Drawables

Drawable resources include bitmaps and NinePatch (stretchable PNG) images. They are stored as individual files in the res/drawable folder. The resource identifier for a bitmap resource is the lowercase filename without an extension.

The preferred format for a bitmap resource is PNG, although JPG and GIF files are also supported.

NinePatch (or stretchable) images are PNG fi les that mark the parts of an image that can be stretched. NinePatch images must be properly defined PNG files that end in .9.png. The resource identifier for NinePatches is the filename without the trailing .9.png.

A NinePatch is a variation of a PNG image that uses a 1-pixel border to define the area of the image that can be stretched if the image is enlarged. To create a NinePatch, draw single-pixel black lines that represent stretchable areas along the left and top borders of your image. The unmarked sections won’t be resized, and the relative size of each of the marked sections will remain the same as the image size changes.

Layouts

Layout resources let you decouple your presentation layer by designing user-interface layouts in XML rather than constructing them in code. The most common use of a layout is to defi ne the user interface for an Activity. Once defined in XML, the layout is “inflated” within an Activity using setContentView, usually within the onCreate method.

Animations

Android supports two types of animation. Tweened animations can be used to rotate, move, stretch, and fade a View; or you can create frame-by-frame animations to display a sequence of drawable images. Defining animations as external resources allows you to reuse the same sequence in multiple places and provides you with the opportunity to present an alternative animation based on device hardware or orientation.

An animation can be defined for changes in alpha (fading), scale (scaling), translate (moving), or rotate (rotating).

Each of these animation types supports attributes to define what the sequence will do:

Alpha fromAlpha and toAlpha Float from 0 to 1

Scale fromXScale/toXScale Float from 0 to 1

fromYScale/toYScale Float from 0 to 1

pivotX/pivotY String of the percentage of graphic width/height from 0% to 100%

Translate fromX/toX Float from 0 to 1

fromY/toY Float from 0 to 1

Rotate fromDegrees/toDegrees Float from 0 to 360

pivotX/pivotY String of the percentage of graphic width/height from 0% to 100%

You can create a combination of animations using the set tag. An animation set contains one or more animation transformations and supports various additional tags and attributes to customize when and how each animation within the set is run.

The following list shows some of the set tags available:

❑ duration Duration of the animation in milliseconds.

❑ startOffset Millisecond delay before starting this animation.

❑ fi llBefore True to apply the animation transformation before it begins.

❑ fi llAfter True to apply the animation transformation after it begins.

❑ interpolator Interpolator to set how the speed of this effect varies over time.