0% found this document useful (0 votes)
10 views

android unit2

Android applications are built from components such as Activities, Services, Content Providers, Intents, Broadcast Receivers, Widgets, and Notifications, all defined in the application manifest. The manifest file, AndroidManifest.xml, outlines the structure, metadata, and permissions of the application, ensuring proper interaction between components and external applications. Key manifest elements include versioning, hardware requirements, screen support, and permission declarations necessary for the application's functionality.

Uploaded by

24250156maithri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

android unit2

Android applications are built from components such as Activities, Services, Content Providers, Intents, Broadcast Receivers, Widgets, and Notifications, all defined in the application manifest. The manifest file, AndroidManifest.xml, outlines the structure, metadata, and permissions of the application, ensuring proper interaction between components and external applications. Key manifest elements include versioning, hardware requirements, screen support, and permission declarations necessary for the application's functionality.

Uploaded by

24250156maithri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

Creating Android

Applications
Working of Android Applications
• WHAT MAKES AN ANDROID APPLICATION?
• Android applications consist of loosely coupled components, bound
by the application manifest that describes each component and how
they interact.
• The manifest is also used to specify the application’s metadata, its
hardware and platform requirements, external libraries, and required
permissions.
• The following components comprise the building blocks for all your
Android applications:
• ‰ Activities — Your application’s presentation layer. The UI of your
application is built around one or more extensions of the Activity class.
Activities use Fragments and Views to layout and display information,
and to respond to user actions. Compared to desktop development,
Activities are equivalent to Forms.
• ‰ Services — The invisible workers of your application. Service
components run without a UI, updating your data sources and
Activities, triggering Notifications, and broadcasting Intents. They’re
used to perform long running tasks, or those that require no user
interaction (such as network lookups or tasks that need to continue
even when your application’s Activities aren’t active or visible.)
• ‰ Content Providers — Shareable persistent data storage. Content
Providers manage and persist application data and typically interact with
SQL databases. They’re also the preferred means to share data across
application boundaries. You can configure your application’s Content
Providers to allow access from other applications, and you can access the
Content Providers exposed by others. Android devices include several
native Content Providers that expose useful databases such as the media
store and contacts.
• ‰ Intents — A powerful interapplication message-passing framework.
Intents are used extensively throughout Android. You can use Intents to
start and stop Activities and Services, to broadcast messages system-
wide or to an explicit Activity, Service, or Broadcast Receiver, or to
request an action be performed on a particular piece of data.
• ‰ Broadcast Receivers — Intent listeners. Broadcast Receivers enable your
application to listen for Intents that match the criteria you specify. Broadcast
Receivers start your application to react to any received Intent, making them
perfect for creating event-driven applications.
• ‰ Widgets — Visual application components that are typically added to the
device home screen. A special variation of a Broadcast Receiver, widgets
enable you to create dynamic, interactive application components for users to
embed on their home screens.
• Notifications — Notifications enable you to alert users to application events
without stealing focus or interrupting their current Activity. They’re the
preferred technique for getting a user’s attention when your application is not
visible or active, particularly from within a Service or Broadcast Receiver. For
example, when a device receives a text message or an email, the messaging
and Gmail applications use Notifications to alert you by flashing lights, playing
sounds, displaying icons, and scrolling a text summary. You can trigger these
notifications from your applications.
INTRODUCING THE APPLICATION MANIFEST
FILE
• Each Android project includes a manifest fi le, AndroidManifest.xml, stored in the
root of its project hierarchy. The manifest defines the structure and metadata of
your application, its components, and its requirements.
• It includes nodes for each of the 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 with other
applications.
• The manifest can also specify application metadata (such as its icon, version
number, or theme), and additional top-level nodes can specify any required
permissions, unit tests, and define hardware, screen, or platform requirements
(as described next).
• The manifest is made up of a root manifest tag with a package attribute set to the
project’s package. It should also include an xmlns:android attribute that supplies
several system attributes used within the file.
• Use the versionCode attribute to define the current application version
as an integer that increases with each version iteration, and use the
versionName attribute to specify a public version that will be displayed
to users.
• You can also specify whether to allow (or prefer) for your application be
installed on external storage (usually an SD card) rather than internal
storage using the installLocation attribute. To do this specify either
preferExternal or auto, where the former installs to external storage
whenever possible, and the latter asks the system to decide.
A Closer Look at the Application Manifest
• The following XML snippet shows a typical manifest node:
• <manifest
xmlns:android=”http://schemas.android.com/apk/res/android”
• package=“com.paad.myapp“
• android:versionCode=“1“
• android:versionName=“0.9 Beta“
• android:installLocation=“preferExternal“>
• [ ... manifest nodes ... ]
• </manifest>
• The manifest tag can include nodes that define the application
components, security settings, test classes, and requirements that make
up your application.
• The following list gives a summary of the available manifest sub-node
tags and provides an XML snippet demonstrating how each tag is used:

• ‰ uses-sdk — This node enables you to define a minimum and


maximum SDK version that must be available on a device for your
application to function properly, and target SDK for which it has been
designed using a combination of minSDKVersion, maxSDKVersion, and
targetSDKVersion attributes, respectively.

• <uses-sdk android:minSdkVersion=”6”
• android:targetSdkVersion=”15”/>
• ‰ uses-configuration — The uses-configuration nodes specify each combination of
input mechanisms are supported by your application. You shouldn’t normally need
to include this node, though it can be useful for games that require particular input
controls.

• You can specify any combination of input devices that include the following:
• ‰ reqFiveWayNav — Specify true for this attribute if you require an input device
capable of navigating up, down, left, and right and of clicking the current selection.
This includes both trackballs and directional pads (D-pads).
• ‰ reqHardKeyboard — If your application requires a hardware keyboard, specify
true.
• ‰ reqKeyboardType — Lets you specify the keyboard type as one of nokeys, qwerty,
twelvekey, or undefined.
• ‰ reqNavigation — Specify the attribute value as one of nonav, dpad, trackball,
wheel, or undefined as a required navigation device.
• ‰ reqTouchScreen — Select one of notouch, stylus, finger, or undefined to specify
the required touchscreen input.
• You can specify multiple supported configurations, for example, a device
with a finger touchscreen, a trackball, and either a QUERTY or a twelve-
key hardware keyboard, as shown here:
• <uses-configuration android:reqTouchScreen=”finger”
• android:reqNavigation=”trackball”
• android:reqHardKeyboard=”true”
• android:reqKeyboardType=”qwerty”/>
• <uses-configuration android:reqTouchScreen=”finger”
• android:reqNavigation=”trackball”
• android:reqHardKeyboard=”true”
• android:reqKeyboardType=”twelvekey”/>
• ‰ uses-feature — Android is available on a wide variety of hardware
platforms. Use multiple uses-feature nodes to specify which hardware
features your application requires.
• This prevents your application from being installed on a device that does not
include a required piece of hardware, such as NFC hardware, as follows:
• <uses-feature android:name=”android.hardware.nfc” />

• You can require support for any hardware that is optional on a compatible
device. Currently, optional hardware features include the following:
• ‰ Audio — For applications that requires a low-latency audio pipeline. Note
that at the time of writing this book, no Android devices satisfied this
requirement.
• ‰ Bluetooth — Where a Bluetooth radio is required.
• ‰ Camera — For applications that require a camera. You can also require (or
set as options) autofocus, flash, or a front-facing camera.
• ‰ Location — If you require location-based services. You can also specify
either network or GPS support explicitly.
• ‰ Microphone — For applications that require audio input.
• ‰ NFC — Requires NFC (near-field communications) support.
• ‰ Sensors — Enables you to specify a requirement for any of the potentially
available hardware sensors.
• ‰ Telephony — Specify that either telephony in general, or a specifi c
telephony radio (GSM or CDMA) is required.
• ‰ Touchscreen — To specify the type of touch-screen your application
requires.
• ‰ USB — For applications that require either USB host or accessory mode
support.
• ‰ Wi-Fi — Where Wi-Fi networking support is required.
• As the variety of platforms on which Android is available increases, so too will
the optional hardware. You can find a full list of uses-feature hardware at
• http://developer.android.com/guide/topics/manifest/uses-feature-element.
html#features-reference.

• To ensure compatibility, requiring some permissions implies a feature


requirement. In particular, requesting permission to access Bluetooth, the
camera, any of the location service permissions, audio recording, Wi-Fi, and
telephony-related permissions implies the corresponding hardware features.
You can override these implied requirements by adding a required attribute
and setting it to false — for example, a note-taking application that supports
recording an audio note:
• <uses-feature android:name=”android.hardware.microphone”
• android:required=”false” />
• The camera hardware also represents a special case. For compatibility
reasons requesting permission to use the camera, or adding a uses-
feature node requiring it, implies a requirement for the camera to
support autofocus. You can specify it as optional as appropriate:
• <uses-feature android:name=”android.hardware.camera” />
• <uses-feature android:name=”android.hardware.camera.autofocus”
• android:required=”false” />
• <uses-feature android:name=”android.hardware.camera.flash”
• android:required=”false” />
• ‰ supports-screens — The first Android devices were limited to 3.2" HVGA
hardware. Since then, hundreds of new Android devices have been launched
including tiny 2.55“ QVGA phones, 10.1" tablets, and 42" HD televisions. The
supports-screen node enables you to specify the screen sizes your application has
been designed and tested to. On devices with supported screens, your application is
laid out normally using the scaling properties associated with the layout files you
supply. On unsupported devices the system may apply a “compatibility mode,” such
as pixel scaling to display your application. It’s best practice to create scalable
layouts that adapt to all screen dimensions. You can use two sets of attributes when
describing your screen support. The first set is used primarily for devices running
Android versions prior to Honeycomb MR2 (API level 13). Each attribute takes a
Boolean specifying support. As of SDK 1.6 (API level 4), the default value for each
attribute is true, so use this node to specify the screen sizes you do not support.
• ‰ smallScreens — Screens with a resolution smaller than traditional HVGA
(typically, QVGA screens).
• ‰ normalScreens — Used to specify typical mobile phone screens of at least HVGA,
including WVGA and WQVGA.
• ‰ largeScreens — Screens larger than normal. In this instance a large screen is
considered to be signifi cantly larger than a mobile phone display.
• ‰ xlargeScreens — Screens larger than large-typically tablet devices.
• ‰ requiresSmallestWidthDp — Enables you to specify a minimum
supported screen width in device independent pixels. The smallest screen
width for a device is the lower dimension of its screen height and width.
This attribute can potentially be used to filter applications from the
Google Play Store for devices with unsupported screens, so when used it
should specify the absolute minimum number of pixels required for your
layouts to provide a useable user experience.
• ‰ compatibleWidthLimitDp — Specifies the upper bound beyond which
your application may not scale. This can cause the system to enable a
compatibility mode on devices with screen resolutions larger than you
specify.
• ‰ largestWidthLimitDp — Specifi es the absolute upper bound beyond
which you know your application will not scale appropriately. Typically
this results in the system forcing the application to run in compatibility
mode (without the ability for users to disable it) on devices with screen
resolutions larger than that specified.
• mode. Wherever possible, ensure that your layouts scale in a way that
makes them usable on larger devices.
• <supports-screens android:smallScreens=”false”
• android:normalScreens=”true”
• android:largeScreens=”true”
• android:xlargeScreens=”true”
• android:requiresSmallestWidthDp=”480”
• android:compatibleWidthLimitDp=”600”
• android:largestWidthLimitDp=”720”/>
• ‰ supports-gl-texture — Declares that the application is capable of
providing texture assets that are compressed using a particular GL
texture compression format. You must use multiple supports-gl-texture
elements if your application is capable of supporting multiple texture
compression formats. You can find the most up-to-date list of supported
GL texture compression format values at
http://developer.android.com/guide/topics/manifest/
• supports-gl-texture-element.html.
• <supports-gl-texture
android:name=”GL_OES_compressed_ETC1_RGB8_texture” />
• ‰ uses-permission — As part of the security model, uses-permission
tags declare the user permissions your application requires. Each
permission you specify will be presented to the user before the
application is installed. Permissions are required for many APIs and
method calls, generally those with an associated cost or security
implication (such as dialing, receiving
• SMS, or using the location-based services.
• <uses-permission
android:name=”android.permission.ACCESS_FINE_LOCATION”/>
• ‰ permission — Your application components can also create
permissions to restrict access to shared application components. You
can use the existing platform permissions for this purpose or define
your own permissions in the manifest.
• To do this, use the permission tag to create a permission definition.
Within the permission tag, you can specify the level of access the
permission permits (normal, dangerous, signature, signatureOrSystem),
a label, and an external resource containing the description that
explains the risks of granting the specified permission.
• <permission android:name=”com.paad.DETONATE_DEVICE”
• android:protectionLevel=”dangerous”
• android:label=”Self Destruct”
• android:description=”@string/detonate_description”>
• </permission>
• ‰ instrumentation — Instrumentation classes provide a test framework
for your application components 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>
• ‰ 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). During development you should include a debuggable attribute set to true
to enable debugging, then be sure to disable it for your release builds.

• The application node also acts as a container for the Activity, Service, Content
Provider, and Broadcast Receiver nodes that specify the application components.

• <application android:icon=”@drawable/icon”
• android:logo=”@drawable/logo”
• android:theme=”@android:style/Theme.Light”
• android:name=”.MyApplicationClass”
• android:debuggable=”true”>
• [ ... application nodes ... ]
• </application>
• ‰ activity — An activity tag is required for every Activity within your
application. Use the android:name attribute to specify the Activity class
name. You must include the main launch Activity and any other Activity
that may 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 define the Intents that can be used
to start the Activity.
• <activity android:name=”.MyActivity”
android:label=”@string/app_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, add a 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:name=”.MyService”>
• </service>

• ‰ provider — Provider tags specify each of your application’s Content


Providers. Content Providers are used to manage database access and
sharing.
• <provider android:name=”.MyContentProvider”
• android:authorities=”com.paad.myapp.MyContentProvider”/>
• ‰ receiver — By adding a receiver tag, you can register a Broadcast Receiver
without having to launch your application first. Broadcast Receivers are like
global event listeners that, when registered, will execute whenever a matching
Intent is broadcast by the system or 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 executed. Each receiver node
supports intent-filter child tags that defi ne the Intents that can be used to
trigger the receiver:
• <receiver android:name=”.MyIntentReceiver”>
• <intent-filter>
• <action android:name=”com.paad.mybroadcastaction” />
• </intent-filter>
• </receiver>
• ‰ uses-library — Used to specify a shared library that this application
requires. Maps, Geocoding, and Location-Based Services,” are packaged
as a separate library that is not automatically linked.
• You can specify that a particular package is required — which prevents
the application from being installed on devices without the specified
library — or optional, in which case your application must use reflection
to check for the library before attempting to make use of it.
• <uses-library android:name=”com.google.android.maps”
• android:required=”false”/>
Creating Resources
• Application resources are stored under the res folder in your project
hierarchy. Each of the available resource types is stored in subfolders,
grouped by resource type.
• Each resource type is stored in a different folder: simple values, Drawables,
colors, layouts, animations, styles, menus, XML files (including
searchables), and raw resources. When your application is built, these
resources will be compiled and compressed as efficiently as possible and
included in your application package.
• This process also generates an R class file that contains references to each
of the resources you include in your project. This enables you to reference
the resources in your code, with the advantage of design-time syntax
checking.
Simple Values
• Supported simple values
include strings, colors,
dimensions, styles, and
string or integer arrays.
• All simple values are stored
within XML files in the
res/values folder.
• Strings
• Externalizing your strings helps maintain consistency within your
application and makes it much easier to internationalize them.
• String resources are specified with 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, respectively, to parts
of your text strings, as shown in the following
• example:
• <string name=”stop_message”><b>Stop.</b></string>
• Colors
• Use the color tag to define a new color resource. Specify the color value
using a # symbol followed by the (optional) alpha channel, and then the
red, green, and blue values using one or two hexadecimal numbers with
any of the following notations:
• ‰ #RGB
• ‰ #RRGGBB
• ‰ #ARGB
• ‰ #AARRGGBB
• The following example shows how to specify a fully opaque blue and a
partially transparent green:
• <color name=”opaque_blue”>#00F</color>
• <color name=”transparent_green”>#7700FF00</color>
• 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 identifier describing the scale of your
dimension:
• ‰ px (screen pixels)
• ‰ in (physical inches)
• ‰ pt (physical points)
• ‰ mm (physical millimeters)
• ‰ dp (density-independent pixels)
• ‰ sp (scale-independent pixels)
• Styles and Themes
• Style resources let your applications maintain a consistent look and feel by
enabling you to specify 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 defined. The tag itself
should then contain the value, as shown in the following skeleton code.
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<style name=”base_text”>
<item name=”android:textSize”>14sp</item>
<item name=”android:textColor”>#111</item>
</style>
</resources>
• Drawables
• Drawable resources include bitmaps and NinePatches (stretchable PNG
images). They also include complex composite Drawables, such as
LevelListDrawables and StateListDrawables, that can be defined in XML.

• Layouts
• Layout resources enable you to decouple your presentation layer from your
business logic by designing UI layouts in XML rather than constructing them in
code.
• You can use layouts to define the UI for any visual component, including
Activities, Fragments, and Widgets.
• Once defined in XML, the layout must be “inflated” into the user interface.
Within an Activity this is done using setContentView (usually within the
onCreate method)
• Fragment Views are inflated using the inflate method from the Inflator object
passed in to the Fragment’s onCreateView handler.
• Menus
• Create menu resources to design your menu layouts in XML, rather than
constructing them in code.
• You can use menu resources to define both Activity and context menus within your
applications, and provide the same options you would have when constructing your
menus in code.
• When defined in XML, a menu is inflated within your application via the inflate
method of the MenuInflator Service, usually within the onCreateOptionsMenu
method.
• Each menu definition is stored in a separate file, each containing a single menu, in
the res/menu folder — the filename then becomes the resource identifier.
Using Resources in Code
• Access resources in code using the static R class. R is a generated class
based on your external resources, and created when your project is
compiled. The R class contains static subclasses for each of the
resource types for which you’ve defined at least one resource. For
example, the default new project includes the R.string and
R.drawable subclasses.

• Each of the subclasses within R exposes its associated resources as


variables, with the variable names matching the resource identifiers
— for example, R.string.app_name or R.drawable.icon.
• The value of these variables is an integer that represents each resource’s
location in the resource table, not an instance of the resource itself.
• Where a constructor or method, such as setContentView, accepts a
resource identifier, you can pass in the resource variable, as shown in
the following code snippet:
• // Inflate a layout resource.
• setContentView(R.layout.main);
• // Display a transient dialog box that displays the
• // error message string resource.
• Toast.makeText(this, R.string.app_error, Toast.LENGTH_LONG).show();
Referencing Resources Within Resources
• You can also use resource references as attribute values in other XML
resources. This is particularly useful for layouts and styles, letting you
create specialized variations on themes and localized strings and
image assets. It’s also a useful way to support different images and
spacing for a layout to ensure that it’s optimized for different screen
sizes and resolutions.
• To reference one resource from another, use the @ notation, as
shown in the following snippet:
• attribute=”@[packagename:]resourcetype/resourceidentifier”
• <?xml version=”1.0” encoding=”utf-8”?>
• <LinearLayout
• xmlns:android=”http://schemas.android.com/apk/res/android”
• android:orientation=”vertical”
• android:layout_width=”match_parent”
• android:layout_height=”match_parent”
• android:padding=”@dimen/standard_border”>
• <EditText
• android:id=”@+id/myEditText”
• android:layout_width=”match_parent”
• android:layout_height=”wrap_content”
• android:text=”@string/stop_message”
• android:textColor=”@color/opaque_blue”
• />
• </LinearLayout>
Using System Resources
• The Android framework makes many native resources available, providing
you with various strings, images, animations, styles, and layouts to use in
your applications.
• Accessing the system resources in code is similar to using your own
resources. The difference is that you use the native Android resource
classes available from android.R, rather than the applicationspecific R class.
• The following code snippet uses the getString method available in the
application context to retrieve an error message available from the system
resources:
• CharSequence httpError = getString(android.R.string.httpErrorBadUrl);
• To access system resources in XML, specify android as the package
name, as shown in this XML snippet:
• <EditText
• android:id=”@+id/myEditText”
• android:layout_width=”match_parent”
• android:layout_height=”wrap_content”
• android:text=”@android:string/httpErrorBadUrl”
• android:textColor=”@android:color/darker_gray”
• />
Runtime Configuration Changes
• Android handles runtime changes to the language, location, and hardware
by terminating and restarting the active Activity. This forces the resource
resolution for the Activity to be reevaluated and the most appropriate
resource values for the new configuration to be selected.
• To have an Activity listen for runtime configuration changes, add an
android:configChanges attribute to its manifest node, specifying the
configuration changes you want to handle.
• The following list describes some of the configuration changes you can
specify:
• ‰ mcc and mnc — A SIM has been detected and the mobile country or
network code (respectively) has changed.
• ‰ locale — The user has changed the device’s language settings.
• ‰ keyboardHidden — The keyboard, d-pad, or other input mechanism has been
exposed or hidden.
• ‰ keyboard — The type of keyboard has changed; for example, the phone may
have a 12-key keypad that flips out to reveal a full keyboard, or an external keyboard
might have been plugged in.
• ‰ fontScale — The user has changed the preferred font size.
• ‰ uiMode — The global UI mode has changed. This typically occurs if you switch
between car mode, day or night mode, and so on.
• ‰ orientation — The screen has been rotated between portrait and landscape.
• ‰ screenLayout — The screen layout has changed; typically occurs if a different
screen has been activated.
• ‰ screenSize — Introduced in Honeycomb MR2 (API level 12), occurs when the
available screen size has changed, for example a change in orientation between
landscape and portrait.
• ‰ smallestScreenSize — Introduced in Honeycomb MR2 (API level 12), occurs when
the physical screen size has changed, such as when a device has been connected to
an external display.
• <activity
• android:name=”.MyActivity”
• android:label=”@string/app_name”
• android:configChanges=”screenSize|orientation|keyboardHidden”>
• <intent-filter >
• <action android:name=”android.intent.action.MAIN” />
• <category android:name=”android.intent.category.LAUNCHER” />
• </intent-filter>
• </activity>
• Adding an android:configChanges
attribute suppresses the restart for the
specified configuration changes, instead
triggering the onConfigurationChanged
handler in the associated Activity.
• Override this method to handle the
configuration changes yourself, using
the passed-in Configuration object to
determine the new configuration
values, as shown in Listing 3-6. Be sure
to call back to the superclass and reload
any resource values that the Activity
uses, in case they’ve changed.
UNDERSTANDING AN APPLICATION’S PRIORITY
AND ITS PROCESS’ STATES
• The order in which processes are killed to reclaim resources is
determined by the priority of their hosted applications. An
application’s priority is equal to that of its highest-priority
component.
• If two applications have the same priority, the process that has been
at that priority longest will be killed first. Process priority is also
affected by interprocess dependencies; if an application has a
dependency on a Service or Content Provider supplied by a second
application, the secondary application has at least as high a priority as
the application it supports.
• The following list details each of the
application states shown in Figure ,
explaining how the state is determined by
the application components of which it
comprises:
• ‰ Active processes — Active (foreground)
processes have application components the
user is interacting with. These are the
processes Android tries to keep responsive
by reclaiming resources from other
applications. There are generally very few of
these processes, and they will be killed only
as a last resort.
• Active processes include the following:
• ‰ Activities in an active state — that is, those in the foreground
responding to user events.
• ‰ Broadcast Receivers executing onReceive event handlers.
• ‰ Services executing onStart, onCreate, or onDestroy event handlers.
• ‰ Running Services that have been flagged to run in the foreground.

• ‰ 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 be killed only under extreme circumstances to allow active
processes to continue.
• ‰ Started Service processes — Processes hosting Services that have been
started. Because these Services don’t interact directly with the user, they
receive a slightly lower priority than visible Activities or foreground Services.
Applications with running Services are still considered foreground processes
and won’t be killed unless resources are needed for active or visible
processes. When the system terminates a running Service it will attempt to
restart them (unless you specify that it shouldn’t) when resources become
available.
• ‰ Background processes — Processes hosting Activities that aren’t visible
and that don’t have any running Services. There will generally be a large
number of background processes that Android will kill using a last-seen-first-
killed pattern in order to obtain resources for foreground processes.
• ‰ Empty processes — To improve overall system performance, Android will
often retain an application in memory after it has reached the end of its
lifetime. Android maintains this cache to improve the start-up time of
applications when they’re relaunched. These processes are routinely killed, as
required.
INTRODUCING THE ANDROID APPLICATION
CLASS
• Your application’s Application object remains instantiated whenever your application
runs. Unlike Activities, the Application is not restarted as a result of configuration
changes.
• Extending the Application class with your own implementation enables you to do three
things:
• ‰ Respond to application level events broadcast by the Android run time such as low
memory conditions.
• ‰ Transfer objects between application components.
• ‰ Manage and maintain resources used by several application components.

• When your Application implementation is registered in the manifest, it will be


instantiated when your application process is created. As a result, your Application
implementation is by nature a singleton and should be implemented as such to provide
access to its methods and member variables.
Overriding the Application Lifecycle Events
• The Application class provides event handlers for application creation
and termination, low memory conditions, and configuration changes
(as described in the previous section).
• By overriding these methods, you can implement your own
application-specific behavior for each of these circumstances:
• ‰ onCreate — Called when the application is created. Override this
method to initialize your application singleton and create and
initialize any application state variables or shared resources.
• ‰ onLowMemory — Provides an opportunity for well-behaved applications to
free additional memory when the system is running low on resources. This will
generally only be called when background processes have already been
terminated and the current foreground applications are still low on memory.
Override this handler to clear caches or release unnecessary resources.
• ‰ onTrimMemory — An application specific alternative to the onLowMemory
handler introduced in Android 4.0 (API level 13). Called when the run time
determines that the current application should attempt to trim its memory
overhead – typically when it moves to the background. It includes a level
parameter that provides the context around the request.
• ‰ onConfigurationChanged — Unlike Activities Application objects are not
restarted due to configuration changes. If your application uses values
dependent on specific configurations, override this handler to reload those
values and otherwise handle configuration changes at an application level.
• Overriding the Application Lifecycle • @Override
Handlers • public final void onLowMemory() {
• public class MyApplication extends • super.onLowMemory();
Application {
• }
• private static MyApplication
singleton; • @Override
• // Returns the application instance • public final void onTrimMemory(int
level) {
• public static MyApplication • super.onTrimMemory(level);
getInstance() {
• }
• return singleton;
• @Override
• } • public final void
• @Override onConfigurationChanged(Configuration
newConfig) {
• public final void onCreate() {
• super.onConfigurationChanged(newCon
• super.onCreate(); fig);
• singleton = this; • }
• } • }
Building User Interfaces
• FUNDAMENTAL ANDROID UI DESIGN
• User interface (UI) design, user experience (UX), human computer
interaction (HCI), and usability are huge topics.
• Android introduces some new terminology for familiar programming
metaphors that will be explored in detail in the following sections:
• ‰ Views — Views are the base class for all visual interface elements
(commonly known as controls or widgets). All UI controls, including
the layout classes, are derived from View.
• ‰ View Groups — View Groups are extensions of the View class that can
contain multiple child Views. Extend the ViewGroup class to create compound
controls made up of interconnected child Views. The ViewGroup class is also
extended to provide the Layout Managers that help you lay out controls within
your Activities.

• ‰ Fragments — Fragments, introduced in Android 3.0 (API level 11), are used
to encapsulate portions of your UI. This encapsulation makes Fragments
particularly useful when optimizing your UI layouts for different screen sizes
and creating reusable UI elements. Each Fragment includes its own UI layout
and receives the related input events but is tightly bound to the Activity into
which each must be embedded. Fragments are similar to UI View Controllers
in iPhone development.

• ‰ Activities — Activities, described in detail in the previous chapter,


represent the window, or screen, being displayed. Activities are the Android
equivalent of Forms in traditional Windows desktop development. To display a
UI, you assign a View (usually a layout or Fragment) to an Activity.
ANDROID USER INTERFACE FUNDAMENTALS
• All visual components in Android descend from the View class and are
referred to generically as Views.

• The ViewGroup class is an extension of View designed to contain


multiple Views. View Groups are used most commonly to manage the
layout of child Views, but they can also be used to create atomic
reusable components. View Groups that perform the former function
are generally referred to as layouts.
Assigning User Interfaces to Activities
• A new Activity starts with a temptingly empty screen onto which you place your UI. To do
so, call setContentView, passing in the View instance, or layout resource, to display.
Because empty screens aren’t particularly inspiring, you will almost always use
setContentView to assign an Activity’s UI when overriding its onCreate handler.

• The setContentView method accepts either a layout’s resource ID or a single View


instance. This lets you define your UI either in code or using the preferred technique of
external layout resources.
• @Override
• public void onCreate(Bundle savedInstanceState) {
• super.onCreate(savedInstanceState);
• setContentView(R.layout.main);
• }
• You can obtain a reference to each of the Views within a layout using the
findViewById method:
• TextView myTextView = (TextView)findViewById(R.id.myTextView);

• If you prefer the more traditional approach, you can construct the UI in
code:
• @Override
• public void onCreate(Bundle savedInstanceState) {
• super.onCreate(savedInstanceState);
• TextView myTextView = new TextView(this);
• setContentView(myTextView);
• myTextView.setText(“Hello, Android”);
•}
• The setContentView method accepts a single View instance; as a result, you
use layouts to add multiple controls to your Activity.

You might also like