The Android Application Life Cycle
8:44 AM // 0 comments // Sajib Barua // Category: Android Applications //- 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.Active processes include:
- Activities in an “active” state; that is, they are in the foreground and responding to user events. You will explore Activity states in greater detail later in this chapter.
- Activities, Services, or Broadcast Receivers that are currently executing an onReceive event handler.
- Services that are executing an onStart, onCreate, or onDestroy event handler.
-
- 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.
<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>
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);
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
<color name=”opaque_blue”>#00F</color>
<color name=”transparent_green”>#7700FF00</color>
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 relative to a 160-dpi screen
-
sp Scale-independent pixels
These alternatives let you define a dimension not only in absolute terms, but also using relative scales that account for different screen resolutions and densities to simplify scaling on different hardware.
The following XML snippet shows how to specify dimension values for a large font size and a standard border:
<dimen name=”standard_border”>5px</dimen>
<dimen name=”large_font_size”>16sp</dimen>
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 defined. The tag itself should then contain the value, as shown in the skeleton code below:
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<style name=”StyleName”>
<item name=”attributeName”>value</item>
</style>
</resources>
Styles support inheritance using the parent attribute on the style tag, making it easy to create simple variations.
The following example shows two styles that can also be used as a theme; a base style that sets several text properties and a second style that modifies the first to specify a smaller font.
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<style name=”BaseText”>
<item name=”android:textSize”>14sp</item>
<item name=”android:textColor”>#111</item>
</style>
<style name=”SmallText” parent=”BaseText”>
<item name=”android:textSize”>8sp</item>
</style>
</resources>
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 fi les 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 defi ned 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 defi ne 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.
NinePatches are a powerful technique for creating images for the backgrounds of Views or Activities that may have a variable size; for example, Android uses NinePatches for creating button backgrounds.
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 define the user interface for an Activity. Once defined in XML, the layout is “inflated” within an Activity using setContentView, usually within the onCreate method.
You can also reference layouts from within other layout resources, such as layouts for each row in a List View.
Using layouts to create your screens is best-practice UI design in Android. The decoupling of the layout from the code lets you create optimized layouts for different hardware configurations, such as varying screen sizes, orientation, or the presence of keyboards and touch screens.
Each layout definition is stored in a separate fi le, each containing a single layout, in the res/layout folder. The filename then becomes the resource identifier.
A thorough explanation of layout containers and View elements is included in the next chapter, but as an example, the following code snippet shows the layout created by the New Project Wizard. It uses a LinearLayout as a layout container for a TextView that displays the “Hello World” greeting.
<?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:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Hello World!”
/>
</LinearLayout>
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.
Each tweened animation is stored in a separate XML fi le in the project’s res/anim folder. As with layouts and drawable resources, the animation’s filename is used as its resource identifier.
An animation can be defined for changes in alpha (fading), scale (scaling), translate (moving), or rotate (rotating).
Alpha | fromAlpha and toAlpha | Float from 0 to 1 |
Scale | fromXScale/toXScale fromYScale/toYScale pivotX/pivotY | Float from 0 to 1 Float from 0 to 1 String of the percentage of graphic width/height from 0% to 100% |
Translate | fromX/toX fromY/toY | Float from 0 to 1 Float from 0 to 1 |
Rotate | fromDegrees/toDegrees pivotX/pivotY | Float from 0 to 360 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.
-
fillBefore True to apply the animation transformation before it begins.
-
fillAfter True to apply the animation transformation after it begins.
-
interpolator Interpolator to set how the speed of this effect varies over time. To specify an interpolator, reference the system animation resources at android:anim/interpolatorName.
If you do not use the startOffset tag, all the animation effects within a set will execute simultaneously.
The following example shows an animation set that spins the target 360 degrees while it shrinks and fades out:
<?xml version=”1.0” encoding=”utf-8”?>
<set xmlns:android=”http://schemas.android.com/apk/res/android”
android:interpolator=”@android:anim/accelerate_interpolator”>
<rotate
android:fromDegrees=”0”
android:toDegrees=”360”
android:pivotX=”50%”
android:pivotY=”50%”
android:startOffset=”500”
android:duration=”1000” />
<scale
android:fromXScale=”1.0”
android:toXScale=”0.0”
android:fromYScale=”1.0”
android:toYScale=”0.0”
android:pivotX=”50%”
android:pivotY=”50%”
android:startOffset=”500”
android:duration=”500” />
<alpha
android:fromAlpha=”1.0”
android:toAlpha=”0.0”
android:startOffset=”500”
android:duration=”500” />
</set>
Frame-by-Frame Animations
Frame-by-frame animations let you create a sequence of drawables, each of which will be displayed for a specified duration, on the background of a View.
Because frame-by-frame animations represent animated drawables, they are stored in the res/drawble folder, rather than with the tweened animations, and use their filenames (without the xml extension) as their resource IDs.
The following XML snippet shows a simple animation that cycles through a series of bitmap resources, displaying each one for half a second. In order to use this snippet, you will need to create new image resources rocket1 through rocket3.
<animation-list
xmlns:android=”http://schemas.android.com/apk/res/android”
android:oneshot=”false”>
<item android:drawable=”@drawable/rocket1” android:duration=”500” />
<item android:drawable=”@drawable/rocket2” android:duration=”500” />
<item android:drawable=”@drawable/rocket3” android:duration=”500” />
</animation-list>
Using Resources
As well as the resources you create, Android supplies several system resources that you can use in your applications. The resources can be used directly from your application code and can also be referenced from within other resources (e.g., a dimension resource might be referenced in a layout definition).
It’s important to note that when using resources you cannot choose a particular specialized version. Android will automatically select the most appropriate value for a given resource identifier based on the current hardware and device settings.
You access resources in code using the static R class. R is a generated class based on your external resources and created by compiling your project. 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.
If you are using the ADT plug-in in Eclipse, the R class will be created automatically when you make any change to an external resource fi le or folder. If you are not using the plug-in, use the AAPT tool to compile your project and generate the R class. R is a compiler-generated class, so don’t make any manual modifications to it as they will be lost when the fi le is regenerated.
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 a reference to the corresponding 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 code snippet below:
// 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();
When you need an instance of the resource itself, you’ll need to use helper methods to extract them from the resource table, represented by an instance of the Resources class.
Because these methods perform lookups on the application’s resource table, these helper methods can’t be static. Use the getResources method on your application context as shown in the snippet below to access your application’s Resource instance:
Resources myResources = getResources();
The Resources class includes getters for each of the available resource types and generally works by passing in the resource ID you’d like an instance of. The following code snippet shows an example of using the helper methods to return a selection of resource values:
Resources myResources = getResources();
CharSequence styledText = myResources.getText(R.string.stop_message);
Drawable icon = myResources.getDrawable(R.drawable.app_icon);
int opaqueBlue = myResources.getColor(R.color.opaque_blue);
float borderWidth = myResources.getDimension(R.dimen.standard_border);
Animation tranOut;
tranOut = AnimationUtils.loadAnimation(this, R.anim.spin_shrink_fade);
String[] stringArray;
stringArray = myResources.getStringArray(R.array.string_array);
int[] intArray = myResources.getIntArray(R.array.integer_array);
Frame-by-frame animated resources are infl ated into AnimationResources. You can return the value using getDrawable and casting the return value as shown below:
AnimationDrawable rocket;
rocket = (AnimationDrawable)myResources.getDrawable(R.drawable.frame_by_frame);
At the time of going to print, there is a bug in the AnimationDrawable class. Currently, AnimationDrawable resources are not properly loaded until some time after an Activity’s onCreate method has completed. Current work-arounds use timers to force a delay before loading a frame-by-frame resource.
to be continued . . . . . .

Related posts :
0 comments for this post
Leave a reply
Microsoft Word LaTeX Shortcut...
05-Nov-2020Learn Python...
23-Mar-2019A Mathematical Theory of Comm...
10-Dec-2015The Free Energy Secrets of Co...
26-Dec-2014Electronic refrigeration usin...
23-Nov-2014
- Radhika says:
Nice. Thanks for the great information. I have read many blogs but this blog is really informative....[[More detail]] - arohi patil says:
Two Stage Transformer Oil Filtration Plant - Jhun05 says:
Hi, i really needineed help,isais there anyone who can help me about this kV2c FM45s GE electric...[[More detail]] - arif says:
You possess lifted an essential offspring..Blesss for using..I would want to study better latest...[[More detail]] - Dilip says:
Very informative blog. thank you for sharing . keep posting.[[More detail]]