Anda di halaman 1dari 26

Table of Contents

1. 2. 3. 3.1. 3.1.1. 3.2. 3.2.1. 3.2.2. 3.3. 3.4. 3.5. 4. 4.1. 4.2. 4.2.1. 4.2.2. 4.2.3. 4.2.4. 4.3. 4.3.1. 4.3.2. 4.4. 4.4.1. 4.4.2. 5. 6. 6.1. 6.2. 7. What is Android ? ..................................................................................... 1 What are the features of Android Platform ? .................................................... 1 What is the Architecture of Android ? ............................................................ 1 Linux Kernel ............................................................................................ 2 Key Points:.............................................................................................. 2 Android Runt ime & Core API s ....................................................................... 2 Android Runtime ....................................................................................... 2 Core APIs ................................................................................................ 2 Libraries................................................................................................. 2 Application Framework ............................................................................... 3 Applications ............................................................................................ 3 Android Applications ................................................................................. 3 Fundamentals .......................................................................................... 3 Application Components ............................................................................ 2 Activity .................................................................................................. 3 Services ................................................................................................. 3 Broadcast Receivers ................................................................................... 4 Content Providers ..................................................................................... 4 Activating & Shutdown Components ................................................................ 4 Activating Components: Intents ..................................................................... 4 Shutting Down Components .......................................................................... 5 Others ................................................................................................... 5 The Manifest file ....................................................................................... 5 Intents, Intent Objects and Intent filters .......................................................... 6 Activities & Tasks ..................................................................................... 9 Processes and Threads............................................................................. 10 Process ................................................................................................. 10 Threads ................................................................................................ 11 Switching to Home Screen ........................................................................ 11

List of Figures
Figure 1. Figure 2. Figure 3. Figure 4. Figure 5. Architecture of Android Operating System Building blocks of an Application Boot up process Boot up Process - 2 Home Screen Launching Process 2 2 11 12 13

List of Tables
Table 1. Table 2. Action Constants ................................................................................... 7 Category Constants ................................................................................ 8

Confidential

ii

Version

1. What is Android ?
Android is a soft ware st ack for mobile devices t hat includes an operat ing syst em, middleware and key applications. The Android SDK provides t he t ools and APIs necessary t o begin developing applicat ions on t he Android platform using the Java programming language.

2. What are the features of Android Platform ?


Application framework enabling reuse and replacement of components Dalvik virtual machine optimized for mobile devices Integrated browser based on the open source WebKit engine Optimized graphics powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional) SQLite for structured data storage Media support for common audio, video, and st ill image format s (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, GIF) GSM Telephony (hardware dependent) Bluetooth, EDGE, 3G, and WiFi (hardware dependent) Camera, GPS, compass, and accelerometer (hardware dependent) Rich development environment including a device emulat or, t ools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE

3. What is the Architecture of Android ?

Confidential

Version

Figure 1.

Architecture of Android Operating System

3.1. Linux Kernel


Android relies on Linux version 2.6 for core syst em services such as securit y, memory management , process management , net work st ack, and driver model. The kernel also act s as an abst ract ion layer between the hardware and the rest of the software stack.

3.1.1. Key Points:


Standard Linux 2.6.24 kernel with some enhancements: - Ashmem Binder Logger Low memory killer - Power Management - No glibc support (bionic libc instead - Does not include the full set of standard Linux utilities

3.2. Android Runtime & Core API s


3.2.1. Android Runtime
Libraries provides most of t he funct ionalit y available in t he core libraries of t he Java programming language. Every Android applicat ion runs in it s own process, wit h it s own inst ance of t he Dalvik virt ual machine. Dalvik has been writ t en so t hat a device can run mult iple VMs efficient ly. The Dalvik VM execut es files in t he Dalvik Execut able (.dex) format which is opt imized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included "dx" tool. The Dalvik VM relies on t he Linux kernel for underlying funct ionalit y such as t hreading and lowlevel memory management.

3.2.2. Core APIs


Data structures File access Network Access Graphics Other utilities

3.3. Libraries
Set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework - System C library - a BSD-derived implement at ion of t he st andard C syst em library (libc), t uned for embedded Linux-based devices - Media Libraries - based on Packet Video's OpenCORE; t he libraries support playback and recording of many popular audio and video format s, as well as st at ic image files, including MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
Confidential 2 Version

Surface Manager - manages access t o t he display subsyst em and seamlessly composit es 2D and 3D graphic layers from multiple applications LibWebCore - a modern web browser engine which powers bot h t he Android browser and an embeddable web view SGL - the underlying 2D graphics engine 3D libraries - an implement at ion based on OpenGL ES 1.0 APIs; t he libraries use eit her hardware 3D accelerat ion (where available) or t he included, highly opt imized 3D soft ware rasterizer FreeType - bitmap and vector font rendering SQLite - a powerful and lightweight relational database engine available to all applications

3.4. Application Framework


Provide ability to build extremely rich and innovative applications Free t o t ake advant age of t he device hardware, access locat ion informat ion, run background services, set alarms, add notifications to the status bar, and others Full access to the same framework APIs used by the core applications Designed t o simplify t he reuse of component s; any applicat ion can publish it s capabilit ies and any other application may then make use of those capabilities Platform Services Hardware Services Activity Manager - Telephony Service Package Manager - Bluetooth Service Window Manager - WiFi Service Resource Manager - USB Service Content Providers - Sensor Service View System

3.5. Applications
Applicat ions are t he general applicat ions t hat are pre shipped wit h t he phone or downloaded and installed from the market. Applications make use of Application Framework

4. Android Applications
4.1. Fundamentals
1. Android applications are written in the Java programming language. 2. The compiled Java code along wit h any dat a and resource files required by t he application is bundled by t he aapt tool int o an Android package, an archive file marked by an .apk suffix. 3. This file is used to install the applications on Android device 4. Each Android application lives in its own world: By default, every application runs in its own Linux process. Android st art s t he process when any of t he applicat ion's code needs t o be execut ed, and shut s down t he process when it 's no longer needed and syst em resources are required by other applications.

Confidential

Version

Each process has it s own virt ual machine (VM), so applicat ion code runs in isolat ion from the code of all other applications. By default, each application is assigned a unique Linux user ID. Permissions are set so t hat t he applicat ion's files are visible only t hat user, only t o t he application itself. There are ways to export them to other applications as well. It 's possible t o arrange for t wo applicat ions t o share t he same user ID, in which case they will be able to see each other's files. To conserve syst em resources, applicat ions wit h t he same ID can also arrange t o run in the same Linux process, sharing the same VM.

4.2. Application Components


In Android one applicat ion can make use of element s of ot her applicat ions (provided t hose applications permit it). For example, if your applicat ion needs t o display a scrolling list of images and anot her applicat ion has developed a suit able scroller and made it available t o ot hers, you can call upon that scroller to do the work, rather than develop your own. Your applicat ion doesn't incorporat e t he code of t he ot her applicat ion or link t o it . Rat her, it simply starts up that piece of the other application when the need arises. For t his t o work, t he syst em must be able t o st art an applicat ion process when any part of it is needed, and instantiate the Java objects for that part. Therefore, unlike applications on most other systems, Android applications don't have a single entry point for everything in the application (no main() function, for example). Rather, they have essential components that the system can instantiate and run as needed. There are 4 application components in android

Figure 2.
Confidential

Building blocks of an Application


2 Version

4.2.1. Activity
An activity presents a visual user interface for one focused endeavor the user can undertake. Though t hey work t oget her t o form a cohesive user int erface, each act ivit y is independent of the others. Each one is implemented as a subclass of the Activity base class. An application might consist of just one activity or it may contain several. Typically, one of t he act ivit ies is marked as t he first one t hat should be present ed t o t he user when t he applicat ion is launched. Moving from one act ivit y t o anot her is accomplished by having the current activity start the next one. Each activity is given a default window to draw in. Typically, t he window fills t he screen, but it might be smaller t han t he screen and float on t op of other windows. An act ivit y can also make use of addit ional windows window that presents users with vital information. for example, a pop-up dialog or a obj ect s derived from

The visual cont ent of t he window is provided by a hierarchy of views the base View class.

Each view cont rols a part icular rect angular space wit hin t he window. Parent views cont ain and organize t he layout of t heir children. Leaf views (t hose at t he bot t om of t he hierarchy) draw in the rectangles they control and respond to user actions directed at that space. Thus, views are where the activity's interaction with the user takes place. For example, a view might display a small image and init iat e an act ion when t he user t aps t hat image. Example of Views are but t ons, t ext fields, scroll bars, menu it ems, check boxes, and more. A view hierarchy is placed wit hin an act ivit y's window by the Activity.setContentView() met hod. The cont ent view is t he View obj ect at t he root of t he hierarchy.

4.2.2. Services
A service doesn't have a visual user int erface, but rat her runs in t he background for an indefinite period of time. For example, a service might play background music as the user attends to other matters Each service extends the Service base class. A prime example is a media player playing songs from a play list . The player applicat ion would probably have one or more act ivit ies t hat allow t he user t o choose songs and st art playing t hem. However, t he music playback it self would not be handled by an act ivit y because users will expect t he music t o keep playing even aft er t hey leave t he player and begin somet hing different . To keep t he music going, t he media player act ivit y could st art a service t o run in t he background. The syst em would t hen keep t he music playback service running even aft er t he activity that started it leaves the screen. It's possible t o connect t o (bind t o) an ongoing service (and st art t he service if it 's not already running). While connected, you can communicate with the service through an interface that the service exposes. Like act ivit ies and t he ot her component s, services run in t he main t hread of t he applicat ion process. So t hat t hey won't block ot her component s or t he user int erface, t hey oft en spawn another thread for time-consuming tasks (like music playback).

Confidential

Version

4.2.3. Broadcast Receivers


A broadcast receiver is a component t hat does not hing but receive and react t o broadcast announcements. Many broadcasts originate in system code for example, announcements that the timezone has changed, t hat t he bat t ery is low, t hat a pict ure has been t aken, or t hat t he user changed a language preference. Applicat ions can also init iat e broadcast s for example, t o let ot her applicat ions know t hat some data has been downloaded to the device and is available for them to use. An applicat ion can have any number of broadcast receivers t o respond t o any announcement s it considers important. All receivers extend the BroadcastReceiver base class. Broadcast receivers do not display a user int erface. However, t hey may st art an act ivit y in response t o t he informat ion t hey receive, or t hey may use the NotificationManager t o alert t he user.

4.2.4. Content Providers


A content provider makes a specific set of t he applicat ion's dat a available t o ot her applicat ions. The dat a can be st ored in t he file syst em, in an SQLit e dat abase, or in any ot her manner that makes sense. The cont ent provider ext ends t he ContentProvider base class t o implement a st andard set of methods that enable other applications to retrieve and store data of the type it controls. However, applicat ions do not call t hese met hods direct ly. Rat her t hey use a ContentResolver object and call it s met hods inst ead. A Cont ent Resolver can t alk t o any cont ent provider; it cooperat es wit h t he provider t o manage any int erprocess communicat ion that's involved.

4.3. Activating & Shutdown Components


4.3.1. Activating Components: Intents
The ot her t hree component s act ivit ies, services, and broadcast receivers asynchronous messages called intents. An intent is an Intent object that holds the content of the message. For act ivit ies and services, it names t he act ion being request ed and specifies t he URI of t he data to act on, among other things. For example, it might convey a request for an act ivit y t o present an image t o t he user or let the user edit some text. For broadcast receivers, the Intent object names the action being announced. For example, it might announce to interested parties that the camera button has been pressed. There are separate methods for activating each type of component: An act ivit y is launched (or given somet hing new t o do) by passing an Int ent obj ect to Context.startActivity() or Activity.startActivityForResult(). The responding act ivit y can look at t he init ial int ent t hat caused it t o be launched by calling its getIntent() method. Android calls the activity's onNewIntent() method to pass it any subsequent intents. One act ivit y oft en st art s t he next one. If it expect s a result back from t he act ivit y it 's st art ing, it calls st art Act ivit yForResult ()inst ead of startActivity(). For example, if it st art s an act ivit y t hat let s t he user pick a phot o, it might expect t o be ret urned t he chosen phot o. The result is returned in an Intent object that's passed to the calling activity's onActivityResult() method.
Confidential 4 Version

are act ivat ed by

A service is st art ed (or new inst ruct ions are given t o an ongoing service) by passing an Int ent obj ect t o Context.startService(). Android calls t he service's onStart() met hod and passes it t he Intent object. Similarly, an int ent can be passed t o Context.bindService() t o est ablish an ongoing connect ion bet ween t he calling component and a t arget service. The service receives t he Int ent obj ect in an onBind() call. (If the service is not already running, bindService()can optionally start it.) For example, an act ivit y might est ablish a connect ion wit h t he music playback service ment ioned earlier so t hat it can provide t he user wit h t he means (a user int erface) for cont rolling t he playback. The act ivit y would call bindService() t o set up t hat connect ion, and then call methods defined by the service to affect the playback. An applicat ion can init iat e a broadcast by passing an Int ent obj ect t o met hods like Context.sendBroadcast(),Context.sendOrderedBroadcast(), and Context.sendStickyBroadcast() in any of t heir variat ions. Android delivers t he int ent t o all interested broadcast receivers by calling their onReceive() methods.

4.3.2. Shutting Down Components


A content provider is active only while it's responding to a request from a ContentResolver. A broadcast receiver is act ive only while it 's responding t o a broadcast message. So t here's no need to explicitly shut down these components. Activities, on the other hand, provide the user interface. They're in a long-running conversation with the user and may remain active, even when idle, as long as the conversation continues. Similarly, services may also remain running for a long time. o An act ivit y can be shut down by calling it s finish() met hod. One act ivit y can shut down another activity (one it started withstartActivityForResult()) by calling finishActivity(). o A service can be st opped by calling it s stopSelf() met hod, or by calling Context.stopService(). Component s might also be shut down by t he syst em when t hey are no longer being used or when Android must reclaim memory for more active components.

4.4. Others
4.4.1. The Manifest file
Describes the components that exist in an Android application Principal task of the Manifest file is to inform Android about the components of an Application Manifest file is also bundled into the application package (.apk file) Structured XML file which is named AndroidManifest.xml for all the applications.

4.4.1.1.

Key Tags in the Manifest file:

<manifest> [Root tag/node for the entire package] <uses-permission> [Security permissions required by the package to function correctly] <permission> [Permissions which are published by the package to restrict access for other ackages] <instrumentation> [Declares the availability of unit test code for the package] <application> [Contains all application level details. Only one application tag allowed in the file] <activity> [Facility to interact with the user, typically one screen, required for launching screens ] <intent-filter> [Declares the specific intents which the application supports] <action> [intent action ]
Confidential 5 Version

<category> [Intent category] <data> [data associated with intent eg. URI, MIME type etc] <meta-data> [Meta-data info which can be used by users of the app for data retrieval] <service> [Publishes service provided by the application ] <receiver> [List of external events information which the application requires ] <provider> [Publishes the data storage/retrieval capabilities of the application ]

4.4.1.2.

What does Manifest file do?

It names the Java package for the application. The package name serves as a unique identifier for the application. It describes the components of the application the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched. It determines which processes will host application components. It declares which permissions the application must have in order to access protected parts of the API and interact with other applications. It also declares the permissions that others are required to have in order to interact with the application's components. It lists the Instrumentation classes that provide profiling and other information as the application is running. These declarations are present in the manifest only while the application is being developed and tested; they're removed before the application is published. It declares the minimum level of the Android API that the application requires. It lists the libraries that the application must be linked against. Refer to this URL for more details on Android Manifest File: http://developer.android.com/intl/de/guide/topics/manifest/manifest-intro.html

4.4.2. Intents, Intent Objects and Intent filters


For detailed information on this topic refer: http://developer.android.com/intl/de/guide/topics/intents/intents-filters.html

4.4.2.1. 4.4.2.2.

Intents Intent Object

Refer Section 4.3.1. Intents are explained in detail there.

An Intent Object is a bundle of information Cont ains informat ion t hat is usefull for t he component t hat receives t he int ent . Ex: Act ion t o be taken or Data to act on. Cont ains informat ion t hat is of int erest t o Android plat form. Ex: Cat egory of component and instructions to Launch Etc. An Intent object can contain any of the following:
Confidential 6 Version

4.4.2.2.1. Component Name


Name of the component that should handle the Intent Object of type ComponentName (android.content.ComponentName) This is a combinat ion of t he fully qualified class name of t he t arget component (for example "com.example.proj ect .app.Frenet icAct ivit y") and t he package name set in t he manifest file of the application where the component resides (for example, "com.example.project") This is optional This is set by setComponent(), setClass(), or setClassName() This can be read by getComponent().

4.4.2.2.2. Action
This is a string naming the Action to be performed In case of broadcast intents, the action that took place is reported You can define your own Act ion st rings. It should cont ain t he package name as prefix. Ex: com.example.project.SHOW_COLOR An Action in an Intent Object is set by the setAction() method and read by getAction() Few Action Constants that are already defined are shown in below table Constant ACTION_CALL ACTION_EDIT ACTION_MAIN ACTION_SYNC ACTION_BATTERY_LOW ACTION_HEADSET_PLUG ACTION_SCREEN_ON ACTION_TIMEZONE_CHANGED Target component activity activity activity activity broadcast receiver broadcast receiver broadcast receiver broadcast receiver Action Initiate a phone call. Display data for the user to edit. Start up as the initial activity of a task, with no data input and no returned output. Synchronize data on a server with data on the mobile device. A warning that the battery is low. A headset has been plugged into the device, or unplugged from it. The screen has been turned on. The setting for the time zone has changed.

Table 1. Action Constants

4.4.2.2.3. Data
The URI of the data to be acted on and the MIME type of that data For example, if t he act ion field is ACTION_EDIT, t he dat a field would cont ain t he URI of t he document t o be displayed for edit ing. If t he act ion is ACTION_CALL, t he dat a field would be a tel: URI with the number to call.

Confidential

Version

The setData() met hod specifies dat a only as a URI, setType() specifies it only as a MIME t ype, andsetDataAndType() specifies it as both a URI and a MIME type. The URI is read by getData() and the type by getType().

4.4.2.2.4. Category
A st ring cont aining addit ional informat ion about t he kind of component t hat should handle t he intent. Addition of a Category to Intent Object by calling addCategory() function Removal of a Category from the Intent Object by calling removeCategory() function getCategories() to get the set of all the categories in the Intent Object Constant CATEGORY_BROWSABLE Meaning The target activity can be safely invoked by the browser to display data referenced by a link for example, an image or an e-mail message. The activity can be embedded inside of another activity that hosts gadgets. The activity displays the home screen, the first screen the user sees when the device is turned on or when the HOME key is pressed. The activity can be the initial activity of a task and is listed in the top-level application launcher. The target activity is a preference panel. Table 2. Category Constants

CATEGORY_GADGET CATEGORY_HOME CATEGORY_LAUNCHER CATEGORY_PREFERENCE

4.4.2.2.5. Extras
Key-value pairs for addit ional informat ion t hat should be delivered t o t he component handling the intent. Int ent Obj ect has a series of put () met hods and corresponding get .() met hods for insert ing and reading various types of extra data. Same as a bundle obj ect . Bundle can be insert ed int o Int ent Obj ect using put Ext ras() and read using getExtras().

4.4.2.2.6. Flags
Flags of various sort s. Many inst ruct t he Android syst em how t o launch an act ivit y (for example, which t ask t he act ivit y should belong t o) and how t o t reat it aft er it 's launched (for example, whether it belongs in the list of recent activities). All these flags are defined in the Intent class.

4.4.2.3.

Intent Resolution

Basically there are two types of Intents: o Explicit Intents: designate the target component by its name Typically used for applicat ion-int ernal messages such as an act ivit y st art ing a subordinate service or launching a sister activity Android delivers an explicit int ent t o an inst ance of t he designat ed t arget class. No special strategy is required
Confidential 8 Version

Implicit Intents: do not name a target Often used to activate components in other applications. In t he absence of a designat ed t arget , t he Android syst em must find t he best component (or components) to handle the intent Android does so by comparing t he cont ent s of t he Int ent obj ect t o int ent f ilt ers, st ruct ures associat ed wit h component s t hat can pot ent ially receive int ent s. Filt ers advert ise t he capabilit ies of a component and delimit t he int ent s it can handle. They open t he component t o t he possibilit y of receiving implicit int ent s of t he advert ised t ype. If a component does not have any int ent filt ers, it can receive only explicit int ent s. A component wit h filt ers can receive bot h explicit and implicit intents.

4.4.2.4.

Intent Filter

Obj ect of t he Int ent Filt er (android.content.IntentFilter) class. In Manifest declared by <int ent filter> tag. Used t o inform t he syst em which implicit int ent s t hey can handle, act ivit ies, services, and broadcast receivers can have one or more intent filters. Intent will be filtered either by Action or Category or Data.

5. Activities & Tasks


One activity can start another, including one defined in a different application. Ex:You'd like to let users display a street map of some location. There's already an activity that can do that, so all your activity needs to do is put together an Intent object with the required information and pass it to startActivity(). The map viewer will display the map. When the user hits the BACK key, your activity will reappear on screen. To the user, it will seem as if the map viewer is part of the same application as your activity, even though it's defined in another application and runs in that application's process. Android maintains this user experience by keeping both activities in the same task. A task is what the user experiences as an "application." It's a group of related activities, arranged in a stack. The root activity in the stack is the one that began the task - typically, it's an activity the user selected in the application launcher. The activity at the top of the stack is one that's currently running - the one that is the focus for user actions. When one activity starts another, the new activity is pushed on the stack; it becomes the running activity. The previous activity remains in the stack. When the user presses the BACK key, the current activity is popped from the stack and the previous one resumes as the running activity. A task is a stack of activities, not a class or an element in the manifest file. So there's no way to set values for a task independently of its activities. Values for the task as a whole are set in the root activity. For example, the next section will talk about the "affinity of a task"; that value is read from the affinity set for the task's root activity. All the activities in a task move together as a unit. The entire task (the entire activity stack) can be brought to the foreground or sent to the background. Suppose, for instance, that the current task has four activities in its stack three under the current activity.

Confidential

Version

The user presses the HOME key, goes to the application launcher, and selects a new application (actually, a new task). The current task goes into the background and the root activity for the new task is displayed. Then, after a short period, the user goes back to the home screen and again selects the previous application (the previous task). That task, with all four activities in the stack, comes forward. When the user presses the BACK key, the screen does not display the activity the user just left (the root activity of the previous task). Rather, the activity on the top of the stack is removed and the previous activity in the same task is displayed. The behavior just described is the default behavior for activities and tasks. But there are ways to modify almost all aspects of it. The association of activities with tasks, and the behavior of an activity within a task, is controlled by the interaction between flags set in the Intent object that started the activity and attributes set in the activity's <activity> element in the manifest. Both requester and respondent have a say in what happens. In this regard, the principal Intent flags are: FLAG_ACTIVITY_NEW_TASK FLAG_ACTIVITY_CLEAR_TOP FLAG_ACTIVITY_RESET_TASK_IF_NEEDED FLAG_ACTIVITY_SINGLE_TOP The principal <activity> attributes are: taskAffinity launchMode allowTaskReparenting clearTaskOnLaunch alwaysRetainTaskState finishOnTaskLaunch More Details on Activities and Tasks can be found at http://developer.android.com/intl/de/guide/topics/fundamentals.html#acttask

6. Processes and Threads


When the first of an application's components needs to be run, Android starts a Linux process for it with a single thread of execution. By default, all components of the application run in that process and thread.

6.1. Process
The process where a component runs is cont rolled by t he manifest file. The component elements <activity>, <service>,<receiver>, and <provider> each have a process attribute that can specify a process where that component should run. These at t ribut es can be set so t hat each component runs in it s own process, or so t hat some components share a process while others do not. They can also be set so t hat component s of different applicat ions run in t he same process provided t hat t he applicat ions share t he same Linux user ID and are signed by t he same aut horit ies. The <application> element also has a process at t ribut e, for set t ing a default value that applies to all components. All components are instantiated in the main thread of the specified process, and system calls to t he component are dispat ched from t hat t hread. Separat e t hreads are not creat ed for each inst ance. Consequent ly, met hods t hat respond to t hose calls methods
Confidential 10 Version

likeView.onKeyDown() that report user act ions and t he lifecycle not ificat ions always run in t he main thread of the process. This means t hat no component should perform long or blocking operat ions (such as net working operat ions or comput at ion loops) when called by t he syst em, since t his will block any ot her components also in the process. You can spawn separate threads for long operations. Android may decide t o shut down a process at some point , when memory is low and required by other processes that are more immediately serving the user. Application components running in t he process are consequent ly dest royed. A process is rest art ed for t hose component s when there's again work for them to do. When deciding which processes t o t erminat e, Android weighs t heir relat ive import ance t o t he user. For example, it more readily shut s down a process wit h act ivit ies t hat are no longer visible on screen t han a process wit h visible act ivit ies. The decision whet her t o t erminat e a process, therefore, depends on the state of the components running in that process

6.2. Threads
Even t hough you may confine your applicat ion t o a single process, t here will likely be t imes when you will need t o spawn a t hread t o do some background work. Since t he user int erface must always be quick t o respond t o user act ions, t he t hread t hat host s an act ivit y should not also host t ime-consuming operat ions like net work downloads. Anyt hing t hat may not be completed quickly should be assigned to a different thread. Threads are creat ed in code using st andard Java Thread obj ect s. Android provides a number of convenience classes for managing t hreads Looper for running a message loop wit hin a thread, Handler for processing messages, and HandlerThread for set t ing up a t hread wit h a message loop. More details on Process and Threads can be found at: http://developer.android.com/intl/de/guide/topics/fundamentals.html#procthread

7. Switching to Home Screen


As in most Linux based syst ems at st art up, t he boot loader loads t he Linux Kernel and st art s the init process. Init process starts the following Linux daemons Zygote process Runtime process

Figure 3.
Confidential

Boot up process
11 Version

Linux daemons USB Daemon (usbd) to manage USB connections Android Debug Bridge (adb) to manage ADB connections Debugger Daemon (debuggerd) to manage debug processes Radio Interface Layer Daemon (rild) to manage wireless communication Zygote process A nascent process which initializes a Dalvik VM instance Loads classes and listens for requests to spawn new VM instances Forks on request to create VM instances for managed processes Copy-on-write to maximize re-use and minimize footprint Runtime process Init ializes Service Manager t he cont ext manager t hat handles various service registrations and lookup Registers Service Manager as default context manager for handling services Runtime process sends request for Zygote for start the System Server System Server Runtime process sends request for Zygote to start the System Server Zygote froks a new VM instance for the System Server process and starts the service System Service starts the native system servers e.g. Surface Flinger Audio Flinger These native system servers then register with service manager as IPC service targets. System Service also starts the application framework services e.g. Window manager Telephony service Activity manager Connectivity service These android managed services also register with service manager asIPCservice targets

Figure 4.
Confidential

Boot up Process - 2
12 Version

Aft er syst em server loads all services, t he zygot e creat es t he home applicat ion in a separat e process (also creates a separate instance on Dalvik VM for Home app) Each subsequent application then launched in its own process e.g Contacts, Media Player

Figure 5.

Home Screen Launching Process

8. Android SDK & Eclipse IDE setup


Download Android SDK from http://developer.android.com/sdk/index.html Download Eclipse from http://www.eclipse.org/downloads/

8.1. System Requirements


In order t o first use t he Android SDK code and t ools for development you will of course need a suitable environment develop from. Currently the following operating systems are supported: Windows XP or Vista Mac OS X 10.4.8 or later (x86 only) Linux (tested on Linux Ubuntu Dapper Drake) You will also need to install a suitable development environment such as: Eclipse 3.2, 3.3 (Europa) Android Development Tools plugin (optional) Other development environments or IDEs JDK 5 or JDK 6 (JRE alone is not sufficient) Not compatible with Gnu Compiler for Java (gcj) Apache Ant 1.6.5 or later for Linux and Mac, 1.7 or later for Windows

Confidential

13

Version

8.2. Installation
First you will need t o download t he Android SDK pack .zip archive, once downloaded find a suit able installation location on your machine and extract the zipped files. Please not e: This inst allat ion locat ion will be referred t o as $SDK_ROOT from now on t hrough t his tutorial Alt ernat ively you can add / t ools t o your root pat h which will prevent t he need t o specify t he full pat h t o t he t ools direct ory along wit h enabling you t o run Android Debug Bridge (adb) along wit h other command line tools. To add /tools: Linux 1. Edit the ~/.bash_profile or ~/.bashrc files looking for a line that sets the PATH variable. 2. Add the full path location to your $SDK_ROOT/tools location for the PATH variable. 3. If no PATH line exists you can add the line by typing the following: 4. export PATH=${PATH}:<path to your $SDK_ROOT/tools> Mac OS X 1. In t he home direct ory locat e t he .bash_profile and locat ing t he PATH variable add t he location to your $SDK_ROOT/tools folder. Windows XP / Vista 1. Right click on the My Computer icon and select the properties tab. 2. Select the Advanced tab and click the Environment Variables button. 3. In t he new dialog box dowble-click on Pat h (locat ed under Syst em Variables) and t ype in the full path location to the tools directory. The Android SDK also requires a suit able development environment t o work in, here s t he installation guides for each of the supported environments.

8.3. Android Development Framework


If you choose t o use t he Eclipse IDE as your Android development environment you will have t he opport unit y t o inst all and run a plug-in called Android Development Tools. ADT comes wit h a variet y of powerful t ools and ext ensions t hat will make creat ing, running and debugging your Android applications much easier and faster. In order t o download and inst all ADT you will first need t o configure an Eclipse remot e updat e, t his can achieved via the following steps: 1. Start Eclipse, then select Help > Software Updates > Find and Install.... 2. In the dialog that appears, select Search for new features to install and pressNext. 3. Press New Remote Site. 4. In the resulting dialog box, enter a name for the remote site (e.g. Android Plugin) and enter this as its URL: https://dl-ssl.google.com/android/eclipse/. 5. Press OK. 6. You should now see the new site added to the search list (and checked). 7. Press Finish. 8. In t he subsequent Search Result s dialog box, select t he checkbox for Android Plugin > Eclipse Integration > Android Development Tools and press Next. 9. Read t he license agreement and t hen select Accept terms of the license agreement, if appropriate. 10. Press Next. 11. Press Finish. 12. The ADT plugin is not signed; you can accept the installation anyway by pressingInstall All.
Confidential 14 Version

13. Restart Eclipse. 14. Aft er rest art , updat e your Eclipse preferences t o point t o t he SDK root direct ory ($SDK_ROOT): Select Window > Preferences... to open t he Preferences panel. (Mac OS X: Eclipse> Preferences) 15. Select Android from the left panel. 16. For the SDK Location in the main panel, press Browse... and find the SDK root directory. 17. Press Apply, then OK

8.3.1. Updating the ADT Plugin


To update the ADT plugin to the latest version, follow these steps: 1. Select Help > Software Updates > Find and Install.... 2. Select Search for updates of the currently installed features and press Finish. 3. If any update for ADT is available, select and install. Alternatively: 1. Select Help > Software Updates > Manage Configuration. 2. Navigate down the tree and select Android Development Tools <version> 3. Select Scan for Updates under Available Tasks.

8.4. How-To Use Eclipse To Develop Android Applications


In order t o begin development on your Android applicat ions you will first need t o creat e a new Android proj ect and t hen configure a launch configurat ion. Once complet ed you will have t he capability to write, run and debug your Android creations. The following sect ions below will provide you wit h t he necessary inst ruct ions t o get you up and running wit h Android provided you have inst alled t he ADT plugin (as previously ment ioned) in your Eclipse environment.

8.4.1. Creating A New Android Project


The Android Development Tools plugins kindly provides a Wizard for set t ing up new Proj ect s which will allow us to create new Eclipse projects relatively quickly for either new or existing code. Select File > New > Project 1. Select Android > Android Project, and press Next 2. Select the contents for the project: Select Creat e new proj ect in workspace t o st art a proj ect for new code. Ent er t he proj ect name, t he base package name, t he name of a single Act ivit y class t o creat e as a st ub .j ava file, and a name to use for your application. Select Creat e proj ect from exist ing source t o st art a proj ect from exist ing code. Use t his opt ion if you want t o build and run any of t he sample applicat ions included wit h t he SDK. The sample applicat ions are locat ed in t he samples/ direct ory in t he SDK. Browse t o t he direct ory cont aining t he exist ing source code and click OK. If t he direct ory cont ains a valid Android manifest file, t he ADT plugin fills in t he package, act ivit y, and applicat ion names for you. Press Finish. Once complet ed t he ADT plugin will go ahead and creat e t he following files and folders as appropriate for the type of project selected: src/ A folder that includes your stub .java Activity file. res/ A folder for your resources. AndroidManifest.xml The manifest for your project.
Confidential 15 Version

8.4.2. Creating A Launch Configuration For Eclipse


In order t o be able t o run and debug your own Eclipse applicat ions you must first creat e a launch configurat ion. Simply, a launch config is used t o specify which proj ect t o launch, which act ivit y t o start and the specific emulation options to use. To create a launch configuration for the application, please see the following steps: Select Run > Open Run Dialog... or Run > Open Debug Dialog... as appropriate. In the project type list on the left, right-click Android Application and select New. Enter a name for your configuration. On the Android tab, browse for the project and Activity to start. On t he Emulat or t ab, set t he desired screen and net work propert ies, as well as any other emulator startup options. You can set additional options on the Common tab as desired. Press Apply to save the launch configuration, or press Run or Debug (as appropriate).

8.4.3. Running and Debugging an Eclipse Application


Once bot h st eps 1 and 2 have been complet ed and your proj ect and launch configs are up and running you will now be able to run or debug your application. From t he Eclipse main menu, select Run > Run or Run > Debug as appropriat e. This command will run or debug the most recently selected application. To set or change t he act ive launch configurat ion, use t he Run configurat ion manager, which you can access through Run > Open Run Dialog... or Run > Open Debug Dialog.... Running or debugging the application will trigger the following actions: Starts the emulator, if it is not already running. Compile t he proj ect , if t here have been changes since t he last build, and inst alls t he application on the emulator. Run starts the application. Debug st art s t he applicat ion in "Wait for debugger" mode, t hen opens t he Debug perspective and attaches the Eclipse Java debugger to the application.

8.5. Developing Android Applications with Other IDEs and Tools


Alt hough it is recommended you use Eclipse wit h t he Android plugin t o develop your applicat ions, t he SDK also provides t ools which will enable you t o develop wit h ot her IDE s including int elliJ (alternatively you could just use Eclipse without the plugin).

8.5.1. Creating an Android Project


Bundled wit h t he Android SDK is a program called act ivit yCreat ory. act ivit yCreat or will generat e a number of st ub files for your chosen proj ect alongside a build file. This can be used t o eit her create an Android project for new code or from existing code. For Linux and Mac users t he Android SDK provides a Pyt hon script called act ivit yCreat or.py, wit h Windows users receiving a bt ach script called act ivit yCreat or.bat . The program is used in t he same way regardless of operating system. In order to run activityCreator and create an Android project, follow these steps: 1. In t he command line, change t o t he t ools/ direct ory of t he SDK and creat e a new direct ory for your proj ect files. If you are creat ing a proj ect from exist ing code, change t o t he root folder of your application instead.
Confidential 16 Version

2. Run act ivit yCreat or. In t he command, you must specify a fully-qualified class name as an argument . If you are creat ing a proj ect for new code, t he class represent s t he name of a st ub class t hat t he script will creat e. If you are creat ing a proj ect from exist ing code, you must specify t he name of one Act ivit y class in t he package. Command opt ions for t he script include: --out <folder> which set s t he out put direct ory. By default , t he out put direct ory is t he current directory. If you created a new directory for your project files, use this option to point to it. --ide int ellij , which generat es Int elliJ IDEA proj ect files in t he newly creat ed proj ect Here's an example: /android_linux_sdk/tools$ ./activityCreator.py --out myproject your.package.name.ActivityName package: your.package.name out_dir: myproject activity_name: ActivityName ~/android_linux_sdk/tools$ The act ivit yCreat or script generat es t he following files and direct ories (but will not overwrit e existing ones): AndroidManifest .xml The applicat ion manifest file, synced t o t he specified Act ivit y class for the project. build.xml An Ant file that you can use to build/package the application. src/your/package/name/ActivityName.java The Activity class you specified on input. your_act ivit y.iml, your_act ivit y.ipr, your_act ivit y.iws [only wit h t he -ide int elliJ flag] intelliJ project files. res/ A directory to hold resources. src/ The source directory. bin/ The output directory for the build script. Once complet e you will now be able t o move your folder wherever you choose for development but you ll need t o bear in mind t hen you will need t o use t he adb program in the tools folder in order to send the files to the emulator.

8.5.2. How-To Build An Android Application


Here s how t o use t he Ant build.xml file generat ed by act ivit yCreat or t o build your applicat ion. 1. If you don't have it, you can obtain Ant from the Apache Ant home page. Install it and make sure it is on your executable path. 2. Before calling Ant, you need to declare the JAVA_HOME environment variable to specify the pat h t o where t he JDK is inst alled.Not e: When inst alling JDK on Windows, t he default is t o install in t he "Program Files" direct ory. This locat ion will cause ant t o fail, because of t he space. To fix t he problem, you can specify t he JAVA_HOME variable like t his: set JAVA_HOME=c:\Prora~1\Java\. The easiest solut ion, however, is t o inst all JDK in a nonspace directory, for example: c:\java\jdk1.6.0_02. 3. If you have not done so already, follow the instructions for Creating a New Project above to set up the project. 4. You can now run t he Ant build file by simply t yping ant in t he same folder as t he build.xml file for your proj ect . Each t ime you change a source file or resource, you should run ant again and it will package up the latest version of the application for you to deploy.

8.5.3. How-To Run An Android Application


In order t o run a compiled applicat ion you will first need t o upload t he .apk file t o t he / dat a/ app/ directory in the emulator using the adb tool:
Confidential 17 Version

1. Start the emulator (run $SDK_HOME/tools/emulator from the command line) 2. On t he emulat or, navigat e t o t he home screen (it is best not t o have t hat applicat ion running when you reinst all it on t he emulat or; press t he Home key t o navigat e away from that application). 3. Run adb inst all myproj ect / bin/ <appname>.apk t o upload t he execut able. So, for example, t o inst all t he Lunar Lander sample, navigat e in t he command line t o $SDK_ROOT/sample/LunarLander and type ../../tools/adb install bin/LunarLander.apk 4. In t he emulat or, open t he list of available applicat ions, and scroll down t o select and st art your application. Please Note: When inst alling an act ivit y for t he first t ime you may need t o rest art t he emulat or engine in order for t he act ivit y t o show up in t he applicat ion launcher or before any ot her applicat ion can call. This is usually down t o t he fact t hat t he package manager normally only examines manifests completely on emulator start-up.

8.5.4. How-To Attach a Debugger to Your Application


The following sect ion det ails how t o display debug informat ion direct ly ont o t he screen (for example CPU usage). It also shows you how t o hook up your IDE t o debug running applicat ions on the emulator. The Eclipse plugin aut omat ically at t aches a debugger but you can configure ot her IDE s t o wait on a debugging port by doing the following: Start the Dalvik Debug Monitor Server (DDMS) t ool , which act s as a port forwarding service between your IDE and the emulator. 1. Set opt ional debugging configurat ions on your emulat or, such as blocking applicat ion st art up for an act ivit y unt il a debugger is at t ached. Not e t hat many of t hese debugging opt ions can be used wit hout DDMS, such as displaying CPU usage or screen refresh rat e on the emulator. 2. Configure your IDE t o at t ach t o port 8700 for debugging. We ve included informat ion higher up on how to set up Eclipse to debug your project.

8.5.5. How-To Configure Your IDE To Attach To The Debugging Port


DDMS will aut omat ically assign a specific debugging port for every virt ual machine t hat it det ect s on t he emulat or. You must eit her at t ach your IDE t o t hat port , or use a default port 8700 t o connect to whatever application is currently selected on the list of discovered virtual machines. Ideally your IDE will at t ach t o t he applicat ion running on t he emulat or, showing it s t hreads and allowing you t o suspend t hem, inspect t hem, or set breakpoint s. If you choose t o "Wait for debugger" in t he Development set t ings panel, t his will cause t he applicat ion t o run when Eclipse connect s t herefore you will need t o set any breakpoint s you want before connect ing. If you change t he applicat ion being debugged or t he Wait for debugger t hen t he syst em will kill t he select ed currently running application. This can be handy if your applicat ion is in a bad st at e, you can simply go t o t he set t ings and t oggle the checkbox to kill it.

8.6. Debugging Android


Google Android has a fairly extensive set of tools to help you debug your programs: DDMS - A graphical program t hat support s port forwarding (so you can set up breakpoint s in your code in your IDE), screen capt ures on t he emulat or, t hread and st ack informat ion, and many ot her f eat ures. You can also run logcat t o ret rieve your Log messages. See t he linked topic for more information.
Confidential 18 Version

logcat - Dumps a log of syst em messages. The messages include a st ack t race when t he emulat or t hrows an error, as well as Log messages. To run logcat , see t he linked t opic. ... I/ MemoryDealer( 763): MemoryDealer (t his=0x54bda0): Creat ing 2621440 byt es heap at 0x438db000 I/ Logger( 1858): get View() request ing it em number 0 I/ Logger( 1858): get View() request ing it em number 1 I/ Logger( 1858): get View() request ing it em number 2 D/ Act ivit yManager( 763): St opping: Hist oryRecord{409dbb20 com.google.android.home.AllApps} ... Android Log- A logging class t o print out messages t o a log file on t he emulat or. You can read messages in real t ime if you run logcat on DDMS (covered next ). Add a few logging method calls to your code. To use t he Log class, you j ust call Log.v() (verbose), Log.d() (debug), Log.i() (informat ion), Log.w() (warning) or Log.e (error) depending on t he import ance you wish t o assign t he log message. Log.i("MyAct ivit y", "MyClass.get View() Request ing it em number " + posit ion) You can use logcat t o read these messages Traceview - Android can save a log of met hod calls and t imes t o a logging file t hat you can view in a graphical reader called Traceview. See the linked topic for more information. Eclipse plugin - The Eclipse Android plugin incorporat es a number of t hese t ools (ADB, DDMS, logcat output, and other functionality). See the linked topic for more information. Debug and Test Device Set t ings - Android exposes several set t ings t hat expose useful informat ion such as CPU usage and frame rate.

8.6.1. Debug and Test Settings on the Device


Android enables you t o set a number of opt ions t hat will make it far easier t o t est and debug your applications. To get t o t he development set t ings page on t he emulat or simply go t o Dev Tools >Development Settings. This will in turn open up the development settings page with the following options (among others): Debug app Select s t he applicat ion t hat will be debugged. You do not need t o set t his t o attach a debugger, but setting this value has two effects: It will prevent Android from t hrowing an error if you pause on a breakpoint for a long t ime while debugging. It will enable you t o select t he Wait for Debugger opt ion t o pause applicat ion st art up unt il your debugger attaches (described next). Wait for debugger Blocks t he select ed applicat ion from loading unt il a debugger at t aches. This way you can set a breakpoint in onCreat e(), which is import ant t o debug t he st art up process of an Act ivit y. When you change t his opt ion, any current ly running inst ances of t he select ed applicat ion will be killed. In order t o check t his box, you must have select ed a debug applicat ion as described in t he previous opt ion. You can do t he same t hing by adding waitForDebugger() to your code. Immediat ely dest roy act ivit ies Tells t he syst em t o dest roy an act ivit y as soon as it is st opped (as if Android had t o reclaim memory). This is very useful for t est ing t he onFreeze(Bundle) / onCreat e(android.os.Bundle) code pat h, which would ot herwise be difficult t o force. Choosing t his opt ion will probably reveal a number of problems in your application due to not saving state. Show screen updat es Flashes a moment ary pink rect angle on any screen sect ions t hat are being redrawn. This is very useful for discovering unnecessary screen drawing. Show CPU usage Displays CPU met ers at t he t op of t he screen, showing how much t he CPU is being used. The t op red bar shows overall CPU usage, and t he green bar underneat h it
Confidential 19 Version

shows t he CPU t ime spent in composit ing t he screen. Not e: You cannot t urn t his feat ure off once it is on, without restarting the emulator. Show screen FPS Displays t he current frame rat e. Most ly useful for games t o see t he overall frame rat e t hey are achieving. Not e: You cannot t urn t his feat ure off once it is on wit hout restarting the emulator. Show background Displays a background pat t ern when no act ivit y screens are visible. This typically does not happen, but can happen during debugging. More Details on the Android SDK will be found at http://developer.android.com/sdk/index.html

9. Component Life cycles


Every android component has it s own life cycle. Let s see t he lifecycle of an Act ivit y, Service and Broadcast Receiver

9.1. Activity Lifecycle


An Activity has three states It is active or running when it is in the foreground of the screen (at the top of the activity stack for the current task). This is the activity that is the focus for the user's actions. It is paused if it has lost focus but is still visible to the user. That is, another activity lies on top of it and t hat act ivit y eit her is t ransparent or doesn't cover t he full screen, so some of t he paused act ivit y can show t hrough. A paused act ivit y is complet ely alive (it maint ains all st ate and member informat ion and remains at t ached t o t he window manager), but can be killed by the system in extreme low memory situations. It is stopped if it is complet ely obscured by anot her act ivit y. It st ill ret ains all st at e and member informat ion. However, it is no longer visible t o t he user so it s window is hidden and it will often be killed by the system when memory is needed elsewhere. If an act ivit y is paused or st opped, t he syst em can drop it from memory eit her by asking it t o finish (calling its finish() method), or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state. As an act ivit y t ransit ions from st at e t o st at e, it is not ified of t he change by calls t o t he following protected methods: o void onCreate(Bundle savedInstanceState) void onStart() void onRestart() void onResume() void onPause() void onStop() void onDestroy() The entire lifetime of an act ivit y happens bet ween t he first call t o onCreate() t hrough t o a single final call t oonDestroy(). An act ivit y does all it s init ial set up of "global" st at e in onCreate(), and releases all remaining resources in onDestroy(). For example, if it has a t hread running in t he background t o download dat a from t he net work, it may creat e t hat thread in onCreate() and then stop the thread in onDestroy(). The visible lifetime of an activity happens between a call to onStart() until a corresponding call toonStop(). During t his t ime, t he user can see t he act ivit y on-screen, t hough it may not be in t he foreground and int eract ing wit h t he user. Bet ween t hese t wo met hods, you can maint ain resources t hat are needed t o show t he act ivit y t o t he user. For example, you can regist er a BroadcastReceiver in onStart() t o monit or for changes t hat impact your UI, and unregist er it in onStop() when t he user can no longer see what you are displaying.

Confidential

20

Version

The onStart() and onStop() met hods can be called mult iple t imes, as t he act ivit y alt ernat es between being visible and hidden to the user. The foreground lifetime of an act ivit y happens bet ween a call t o onResume() unt il a corresponding call t o onPause(). During t his t ime, t he act ivit y is in front of all ot her act ivit ies on screen and is int eract ing wit h t he user. An act ivit y can frequent ly t ransit ion bet ween t he resumed and paused st at es for example, onPause() is called when t he device goes t o sleep or when a new act ivit y is st art ed, onResume() is called when an act ivit y result or a new int ent is delivered. Therefore, the code in these two methods should be fairly lightweight

Table 3. Life Cycle of an Activity


Confidential 21 Version

9.2. Service Lifecycle


It can be st art ed and allowed t o run unt il someone st ops it or it st ops it self. In t his mode, it 's st art ed by calling Context.startService() and st opped by callingContext.stopService(). It can st op it self by calling Service.stopSelf() or Service.stopSelfResult(). Only one stopService() call is needed to stop the service, no matter how many times startService() was called. It can be operat ed programmat ically using an int erface t hat it defines and export s. Client s est ablish a connect ion t o t he Service obj ect and use t hat connect ion t o call int o t he service. The connect ion is est ablished by calling Context.bindService(), and is closed by calling Context.unbindService(). Multiple clients can bind to the same service. If the service has not already been launched, bindService() can optionally launch it. A service has lifecycle methods that you can implement to monitor changes in its state o void onCreate() void onStart(Intent intent) void onDestroy() The entire lifetime of a service happens bet ween t he t ime onCreate() is called and t he time onDestroy() ret urns. Like an act ivit y, a service does it s init ial set up in onCreate(), and releases all remaining resources in onDestroy(). For example, a music playback service could creat e t he t hread where t he music will be played in onCreate(), and t hen st op t he thread in onDestroy(). The active lifetime of a service begins wit h a call t o onStart(). This met hod is handed t he Int ent obj ect t hat was passed t o startService(). The music service would open t he Int ent t o discover which music to play, and begin the playback. There's no equivalent callback for when the service stops no onStop() method.

Table 4. Lifecycle of a Service


Confidential 22 Version

9.3. Lifecycle of a Broadcast Receiver


A broadcast receiver has single callback method: void onReceive(Context curContext, Intent broadcastMsg)

9.4. Process and Lifecycles


1. A foreground process is one t hat is required for what t he user is current ly doing. A process is considered to be in the foreground if any of the following conditions hold: o It is running an act ivit y t hat t he user is int eract ing wit h (t he Act ivit y object's onResume() method has been called). o It hosts a service that's bound to the activity that the user is interacting with. o It has a Service obj ect t hat 's execut ing one of it s lifecycle callbacks (onCreate(), onStart(), or onDestroy()). o It has a BroadcastReceiver object that's executing its onReceive() method. Only a few foreground processes will exist at any given t ime. They are killed only as a last resort if memory is so low t hat t hey cannot all cont inue t o run. Generally, at t hat point , t he device has reached a memory paging st at e, so killing some foreground processes is required t o keep t he user interface responsive. 2. A visible process is one t hat doesn't have any foreground component s, but st ill can affect what t he user sees on screen. A process is considered t o be visible if eit her of t he following condit ions holds: o It host s an act ivit y t hat is not in t he foreground, but is st ill visible t o t he user (its onPause() met hod has been called). This may occur, for example, if t he foreground activity is a dialog that allows the previous activity to be seen behind it. o It hosts a service that's bound to a visible activity. A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running. 3. A service process is one t hat is running a service t hat has been st art ed wit h the startService() met hod and t hat does not fall int o eit her of t he t wo higher cat egories. Alt hough service processes are not direct ly t ied t o anyt hing t he user sees, t hey are generally doing t hings t hat t he user cares about (such as playing an mp3 in t he background or downloading dat a on t he network), so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes. 4. A background process is one holding an act ivit y t hat 's not current ly visible t o t he user (t he Act ivit y obj ect 's onStop() met hod has been called). These processes have no direct impact on t he user experience, and can be killed at any t ime t o reclaim memory for a foreground, visible, or service process. Usually t here are many background processes running, so t hey are kept in an LRU (least recently used) list to ensure that the process with the activity that was most recently seen by t he user is t he last t o be killed. If an act ivit y implement s it s lifecycle met hods correct ly, and captures it s current st at e, killing it s process will not have a delet erious effect on t he user experience. 5. An empty process is one that doesn't hold any active application components. The only reason to keep such a process around is as a cache t o improve st art up t ime t he next t ime a component needs t o run in it . The syst em oft en kills t hese processes in order t o balance overall syst em resources between process caches and the underlying kernel caches.

For more details on Process and Lifecycles refer

http://developer.android.com/guide/topics/fundamentals.html#lcycles

Confidential

23

Version

Anda mungkin juga menyukai