You are on page 1of 128
OYCOR AAD Sai Technologies Ph: 9052124499/6699 $ai Technologies #202, Manjeera Plaza, Opp Aditya Trade Center, Ameerpet, HYDERABAD 9652124499, 9052126699 www.saitec Sai Technologies Ph: 9052124499/6699 CONTENTS Chapter 1. What is HPROID ? Chapter 2: tindroid Installation Chaptyr 3 “Android pplication & Components Chapter 4: tindroidMonifest.xml Chaptgr 5: Intents Chapter 6 :agouts Chmplye 7: User Interfaeg Components, Chapter 8 : Background Services Chapter 9 : Broadeast Reegivers jee au Opp ya eae Ct Page 2 uo Ys eye Sai Technologies Ph: 9052124499/6699 Chapter 1: What Is Android? Android is a mobile operating system that is based on a modified version of Linux. ft was rigiually developed by a startup of the same name, Android, Ine. In 2005, as port of its strategy to enter the mobile space, Google purchased Android and took over its development werk (as w development ream), Guugle wanted Android to be open and free; henee, most of the Androitl code was released under lie opeu-source Apa License, wi iy meana thai anyone who wants to we Android ean do 20 by Uuwutouding the fall Android source code. Morcoyer, vendors (Iypically hardware manufacturers) con sid their own proprietary extensions 10 Android and customize Android to differentiave their products fiom others. This simple development model makes Android very attractive and hae thue piqued the cted by the phenomendn of “Apple's iPhone, a hugely successful product tnat revolutionized the smartphone industry, Such companies include Motorola and Sony Eriesson, which for many years have been developing their own mobile operat yyolems. When the iPhone was launched, many of these manufacturers had to scramble to find new ways of revitalizing their products. These manufacturers see Android as.a soluuon — they wll continue to design their own hardware and use Android as the operating system that powers it ‘The main advantage of adopting Android i + Ttoffers a unified approach ta appl ‘ion elovelapment Developers need only develop for Android, and thew applications should be able to run on rnumercus diferent deviees, as lang as the devices are powered using Android. In the world of smart puones, applicanons ard the most ihpottant part of the suecess chain Device manutactoers therefore see Android as their best hope to challenge tie oaslaught of the Phone, whieh already commands a large hase of applications, Android is a combination of three components: 1 A tree, apen-sonece operating system for moe devices + An open-source evelopment platform for creating mobile applications. © Devices, particularly mobile phones, that mn the Android operating system and the applications created tor i ; Native Android Applications 202, wajera Pasa, opp aoa Tre Canes ameerpet ‘wonrsehedinns Page 3 Sai Technologies Ph: 9052124499/6699 Ausdivid plus will uorinally voue with a suite of gene ie preinstalled applications iat ate putt of the Andrvid Open Source Project (AOSP), including, bc nut aecessarily Tinted Ww, + Anesnail client An SMS munageient application =A full PIM (personal information inanagemend) suite ineiuding a xd CONLLTS List ° + A Webkit-ased web browser oO + Aimusic player and pire gallery : * Acament and video recording application + ‘Phe hone sereen Analarm clock * Acalculator oO 8 a In many cases Androl devices wl aso ship sth the fllowing proprietary Google mobite - applications: iid +The Anu Manke len for dwnlaalng sind Ano! ppliaions oO A fully ured inobile Google Maps applicaciun includ an uieb-s magn site view. wie cos 8 Tae Oni a esi - 3 The Google Talk instantsmessazine client oO The YouTube video player 2vndi gid SDK Features ‘The tue appeal of Andioid as a development cnvisonment lies in the APIs i provides. + Nolicensing, distibution, or development fees or release approval processes + WitPiardware access + GSM, EDGE, and 3G networks for telephony or data tansfer, enabling you tw ike er receive calls or SMS messages, or to send and reuieve data acioss mobile nevworks. Compichensive APIs foc location-based services such as GPS Full wultimedia hardware wontiol, including playbock aud recording with the canner and itrophoue APIs for using seusor Irardwate, i ding accelerometers and dhe compass Libraries for using Bluetouth for peer-to-peer data ansfer IPC message passing Shared data stores — ee 1202. Majeera Plaza, Opp Aaya Trade Cente. Amerpet vonsitechoscom Page 4 J 3 2 sal Technologies project, much like any other Java project. ‘The specifies, though, are Fairly unique to Androvl and wh 17202 2sjera lana Opp Aya Teade Center Ameerpet Ph: 9052124499/6699 Background applications and processes Home sereen Widgets, Live Folders, and LiveWallpaper ‘The ability to integrate epplication search results into the system search ‘An integrated open source HTMLSWebKit-baced browser Pall support for applications that integrate map controls as part of their user interfnce Mobile ptimsized hardware avcelexered path-b A12D graph abeory ‘ane support for 3D graphies using OpenGI. ES 2.0 Medtia ibrar je for playing and reeorlin 4 variety of audioivideo or stil imag Localization through a dynamic resource framework, ‘An application framework thet encourages reuse of application eoraponents and the replacement cof native applications niroid Project Structure ‘The Android build eystem is organized around a specifie directory your Android prepare the actual apphcanion that will ney on the sevice ar enlator When yon create a new Anriroxd project we get hve key items in the project's root directory + Androidivtanitet xml, which ie.n XME Ge decershing,the application being bait and what components — activities, se~vices, eic. ~ are being supplied by that application + build.xinl - which is an Ant script for compiling the application and installing t en the device + bin - which holds the application once it is compiled + sre which holds the Java source code for the application. + res - which holds "resources", such as icons, GUI layouts, and the like, that get packaged with the compiled Java in the application + assets - which hold other static files you wish packaged with the application for deployment onto the device ‘We will also find that your project has 2 res! directory tree. This, holds “resources” ~ static files that are packaged along with your application, either in their oniginal form or, occasionally, in a reprocessed form. Some of de subdirectories you will find or create under res include: + residrawable/ for images (PNG, JPEG, etc.) + resflayoud/ for XML-based UI layout specificaticas + res/raw/ for general-purpose files + resivalues/ for strings, dimensions, and the like ‘ res/xml/ for other general-purpose XML. files you wish to ship ‘ww saherheoscom Page 5 Sai Technologies Ph: 9052124499/6699 he Daivik Virtual Machine (DVI) One of the kay elements of Android i6 the Dalvie Vor Machine. Ka er than se 9 iradtnonal Java virtual machine (VM)'sneh as Java ME (lava Maile Kaition), Android uses its own custom VM designed to ensure that multiple imstances rn etfierently on a si Je device. ‘The Dalvik VM ses the device's underlying Linux kernel to handle low-level finsetiquality includ threading, and process and! memory naanagement. It's also possible to rita CC applications that tun directly on the inux OS, underly All Android hardware and systom service access is managed wing Dalvik ss 9 miele Wer By ws VM tg host application execution, developers have sn abswaction layer that ensures they never have io. ‘worry about a particular hardware implementation, The Dalvik Vi executes Dalvik executable files, a format optimized to ensure minimal memory fooiprin. We evesiades forming a Janguage compiled slassas using the tools supplied within the SDK. Android Architecture a Stoosger a Nastaser isda ! conta) RAD Se (Romapmer) (uyp owe: }( ‘The Android OS is roughly divided into five sections in four main layers: = Linux kernel —- This’ is the kemel on which Android is based. This layer contains all the lowlevel device drivers for the various hardware components of an Android device., + Libraries These contain all the code that provides the mein feotures of an Android OS. For ‘example, the SQLite library provides database support 90 thet an epplication con use it for data storage. The WebKit library provides functionalities for web browsing, Android runtime — At the same layer as the libraries, the Andgoid runtime provides a set of ‘core libraries that enable developers to write Android apps using the Java programming language. Nee ed 14202 Macca Plas Opp Adi Tad Cntr, Amserpst menaschnoscom Page 6 ai Technologies Ph: 9052124499/6699 The Android runtime also includes the Dalvik virtual wachine, which evables every Audivid pplication to run in its own process, with its owu instance OF the Delvik vitual machine {Android applications are compiled into the Daivik executables). Dalvik is @ spevishiced viriuai machine designed specifically for Android and optimized for battery-powered mobile devices \with limited memory and CPU Application framework — Exposes she various capabitities of the Andruld OS 1 application «uevelopers so that they ean make use of them in dei applications. Applications — At this top layer. you will-find applications chat ship with the Android device suen hone, Contacts, Browser. etc.), 28 well aS applications that you download, and instal from the Android Market Tede Cee Aner ssiehnescom Page 7 Sai Technologies Ph: 9052124499/6699 Chapter 2 : Android Installation? Because Ansiroid applications run within the Dalvsk vartual mschine, you enn write themn on any platform that eupposts the developer tools. This currently includes the following + MicrosoftWindows (XP or later) + Mac O8.X 10.4.8 or later (otel chips only) To yet started, you'll need to download and install the follow’ The Android SDK + favs Developm t Kit IDK) $ oF 6 Dowload the latest IDK from Sun st hitp-Yjava,cun comiavase’sownloadslindes jap Bowuloa: ailing the SDK download the larect version of the SDK. for nent platform fom Andeoid development homeps o ot hupu/developer.ondroid comiedlsindes him! lhe SDK. is presented a2 a ZIP file containing only the latest vorsion wl the Android developer tools, Install it by unzipping the SDK. into 9 new folder Before we can begin development you need to add at least one SDK. Platform; do this on Windows by running the “SDK Setup.exe” axecuiable, or on MacOS or Linas by running the “android” executable in the tdols subfolder. . Im the sercen that appears, select the “Available Packages" option om the left panel, and then select the SDK. Plattormn versions yon wish to mstall m the “Souter , Packages, and Archives" panel on the right The selected plattorm will then be downtearled ta yonr SDK insiallanon folder and will contain the API hbranes, documentation, ari! several campie apphieations Developing with Eclipse Using Kchpse with the ADI plugcin for yonr Anctroxd developiment offers some significant advantages. + Echpse 1s an open-source IDE (integrated development envwonment) particulatly popular for diva, developmen: + les available for download for each of the development platforms supported by Android Windows, MaclS,andLinux) from the Kelipse foundation homepage: www.eclipse.org/downloads! ‘There are many variations available; the following is the recommended configuration for Android: + Eclipse 3.4 or 3.5 (Galileo) + Eclipse IDT plug-in + wst 1202 Mara ln Op Ala Tradl Ces, nero, wsaecotcon Pape 8 wu} eur J Sai Technologies Ph: 9052124499/6699 WST and the JDT plug in are inchided in most Eelipte IDE packages. Installing Eclipse consists of uncompressing the downloed into a new folder. When that’s done, run the eclipse executable, When it starts for the first time, create a new workspace for your Android development projects. Installing the ADT Plag-In Install the developer teols plug-in by f owing these steps: 1. Select Help © Install New Software... fiom within Lelipse, 2.19 the resulting dialog box enter the following address into the Work WWith text entry box snd press Enter: hups:/d-ssl google.convandroideclipse/ ° 3. Eclipse will now search for the ADT plugein, When finitied it will display dhe available pitogin, Selcet i by clicking dhe checkbox next wo the Developer Tuols root ode, ant click Neat 4. Eclipse will now downluad the plus-in, Whew it’s fivished, ensure buds He Autivid DDMS: and Android Develuoes Tuoly pluscius ate yclevted una click Nest, Red und dicn Accept dhe (cts ufc ligeuse aziccineut, ond lick Nest ana thea Finish, As the ADT plug-in ig not signed, you'll be prompted belore the installation continues 6. When installation is complete you'll have to restart Eelipse and update the ADT preferences. Restart aud select Window % Preferences... (or Eelipse & Preferences for MacOS), 7. Thea select Android from the left panel 8. Click Browse... and navigate 1 the folder into which you unzipped the Android SDK: ‘hen click Apply. The list will chen update ro display each of the available SDK cargers. us in Pigure 2-3. Click OK to complete the SDK instalation. 4202, Majnera Plas Opp lity Trade Contr eoerpot ee erhanecam Page 9 Sai Technologies Ph: 9052124499/6699 sepia uke et soos uransauceoree de |) teapesencesr | sate |e Creating Your First Android Application You've downloaded the SDK, installed Eclipse, and plugged in the plug-in. You're now ready to tart programming for Android. Start by ereating a new project and setting up your Eclipse run and debug cconfigursti Starting a New Android Project To create a new Android project using the Android New Project Wizard, do the following: 1.Scect File ® New © Project. 2, Seleet the Android Project application type from the Android folder and click Newt. 3. In the dialog that appears (shown in Figure 2-4), emter he details for your new project. The a — #202 sera as, Opp Aliya Trade Cntr Amecrpt sen atectnescom Page 10 a oD a sai Technotogies Ph: 9052124499/6699 “Project name'” is the name af your project fil; the “Package name’” specifies its java package: Create Activity lets you specify the name of a class that will be your initial Activity; and the “Application name” isthe friendly name for your application. “Min SDK Version” lets you specify the minimum version ofthe SDK. that your application will run on. When you've encered the details, click Finish, | now andoid Project peopetnem oir eens venit | Tins eto Opn swrestroket 45 Laces droowonerswcceronet da 3 \ 4 1 cronies if Asotin ew } 4 I) sae (Creating a Lanneh Contigneation ‘Lanneh configurations let you specify runtime options for nunn:ng and debugging applications Lising a ‘ayneh configuration yon can speci the following . +The Project and Activity to launch = The virtual device and enmlator options to nse + Inputioutpnt settings (ineluding console defaults) ‘We can specity different launch canhgurations for running snd deboggig applicatrens. ‘The following steps show how to create a Iannch configuration for an Android application: Cee EEE eeeemeend #202 Mojeea Pla, Opp Ait, Tne Cone, Ameer we stochncecom Page 11 Sai Technologies Ph: 9052124499/6699 1. Select Run Configurations... or Debug Configurations... from the Run meno. 2. Right-click Android Appli ion on the project type list, and select New. 3. Enter a name forthe configuration. You ean ercate multiple configurations for each project, so ercate a descriptive title that will help you identify this particular setup, 4. Now choose your startup options. The first (Andy jl} tab Hels you select the project wy run andl the Activity that you want zo start when seu vn (or debuy) che veplicatio, 5. Use the Target tub shown in Piguue 2-6 to seleut the defauls vietwal device wo lawnelt uit et select mannal to select u device or AVD each time Pivives ica trond eam 1 Lounet, Deteun aetsig Launch: Fo ning oon | {ever Finslly, set any aeitional properties n the Comman tab 7. Click Apply, and your tanmch configuration will he saved. Ra Applications > yning and Debugging Your Android cts Ores | ia | - ‘coe ieee Bs) fc | Bown cece ‘#202, Majeera Plaza, Opp Aditya Trade Center, ameerpet ‘www sartechnos.com Page 12 o oO ocoeunuceo a 0 wy vuEU we w& OS sai Technologies Ph: 9052124499/6699 You've created your first project and created the run and debug configurations for it. Before making any changes, test your installation ard configurations by running and debug Frou the Run meia select Rum or Debug to Inunch the most recently selected cunt ¢ Hello World project wativu, or select Run Configurations u: Debug Configurations to select a specific configuration to use. 1202, sere Plana Op Adi Trade enter meeret snnsnteeessom Page 13 Sai Technologies Ph: 9052124499/6699 Chapter 3: Andzoid Application & Activities An Activity is on application component thot provides a screen with which ean interet in order to do something, such as dial the phone, take 0 photo, send.an ennai, or view a map. Each activity is ssiven a window in which to draw its user interfuee, The window typically fills the sercen, but may Le smaller than the sercen and Moat en tep of ot An application usually cuusivis of multiple activities Uhat are Yoosely bound wo each other. Tyivally, one activity in au application is specified ay de “wusin” eurivigs, » the user whe launching be application for die Gist time, Ewch activity can ilven sian anoiher activity tm order to perform different actions. Euch cine a mew activity starts, che previous activity is stopped, bu the system reserves the wetivity in a stack (ihe "back slack"), Wht a new seus ey slants. 1 is Homo the back and wakes user Fucus, The Wick stick ables wy the basic "ast in, rst ou when ihe user is done wil he cuttent actiaty and presses dhe BACK hey, it is popped om he s (osad Ceoituseay anid the previnus activity resumes, (The back stack is discussed wore iu the Tasks and Back Stick docuen.) When an activity is stopped because a new activi sianis, iis notified of this change in state through the ‘acuity iecyele calback mediods. There are several callback methods thai an activity might veveive, due to a change in its stste—whether the system is crcating it, stopping it, resuming it, or desiroyin it ‘and each callback provides you the opportunity to perform specitic work that’s appropriate to that staie change. For instance, when stopped, your activity shoutd release any large objeeis. such as neiwork or utabase connections. When the activity resumes, you Chu reucquire the necessary resources and resume ‘aciions hat were interrupted. Thesé state transitions are all pant of he activity lifecycle. “The rest of this document diseusses the hasies af how to build and use an activity, inehncing a complete discussion of how the activity lifecycle works, so you can properly manage the transition helween various activity states. #202, Maja Maa Op iy Ted Conte, Ace snstitechoscon Page 14 Www we eeeuUwY Sai Technologies Ph: 9052124499/6699 i Creati an Activity To create an activity, you must create © of Activity (or an existing subclass of it). In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecyele, such as when the activity is be reated, steppal, resumed, or destroyed. The two most important callback methods are onCreatel ‘You must implement this method. The system calls this when creating your sénvity. Within your implementation, you should initiaiize the essential components of your activity. Ninst importantly, this is where you must call seiContentView!) to define the layout for the activity’s user interface, onPsuse() ‘The system calls this method as the first indication that the user is leaving your activity (thongh it oes not always mean the activity s being destroyed), This is usually where you shen comment arly changes that should ne persisted beyond the current user session (hecanse the iser might not come hack). ‘Where are several other lifecycle callback methods that you should use in order to provide a fluid user ‘experience between activities and handle unexpected interuptions that cause your activity to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in the section about the Activity Life en, oe 1202, ajera Dana Opp Aja Tends Certer Amerpt eatechneecom Page 15 Sai Technologies Ph: 9052124499/6699 Anvplementing a user Interface he user imtertace tor an activity 9s provirled by a merarchy of views—onjerts denved iroin the View. class, Each view controls a particular rectangulor space wathia the activaty's window and ean respond to user interaction. For example, a view might be @ button thot imitates an aetion when the user touches it! Android provides a number of ready made view: Widgs thet you can use to design and organize your Ia i views that provide a vistal (and interactive) elements for the sereen, such a3 a button, text Hold, checkbox, er just sn image. "Layouts" ore views derived from ViewGroup that provide a unique layout model for its child views, such F layout, a grid layout, or relative layout, You ean also subeloss the View and ViewSGroup classes (or exist fond apply then to your activity Iny sabelasses) to eveate your ewn wi eta ond layouts The st Loumon way tv define a layout using views is with an XML layout file saved in your ‘application resources. This way, you can maintain the design of your user juteiface sepanwiely fron de source une that defines the aciivity's behaview. You can set the layout as dhe Ul for your activity with: seiContentView!), passing the resource 'D for the layout, However, you ean also create new ‘your activity code and build a view hierarchy by inserting new Views inte a ViewGroup, then use that Isyout by passing the root ViewGroup to selCéntent View), Fer information about eating a user interface, see die User lates Fuee ducumentaion. Dea ng the activity in the manifest You must declare yonr activity m the mantest ile in order for it to be actessible to the system. To declare your activity, open your manitest hie and add an element asa child of the element bor example: “octivity android:name-".ExempleActivity" > lopplication «> shmazifest > 1102 asjea Plan, Opp Aya Trade Center Ameer emusstechnetcom Page 16 i] ae ° oO o ° eeoooo veEvVvur tw Sai Technologies: Ph: 9052124499/6699 ‘There ate several oer tinbtes that you can include in this element, to fine popes sch asthe label forthe activity, an scom tr te arity, theme to sty the activity’ Hl, The andeietsame sxvibute isthe only required atibute—it species the class ame nf he aenvty Onre yon publish your pplication, you should not ghange this name, Beeause st you do, you nnght break some fnctionauty, euch as application shorteute (read the blow post, Lhines [hat Cannat Change) Sce the Zactivitys element reference for more information shout declaris activity in the manifect Using incent fitiers ‘An Sactivity> element can also specify various inten Glters—using the elenent—in oder to declare how cter application compunents may wctivate i When yon creat 9 new application using the Android SDK tools, he stub,activity that’s created for you Anstomatieally includes an intent filter that declares the activity responds 10 the “main” action andshould be placed in the “launcher” category. The intent filter looks like this: category android:name="android intent.category. LAUNCHER" /> he element specifies that this is the “main” entry point to the application. The clement specifies that this activity shontd be listed in the system's application launcher (io allow users ta lavaneh this activity) If you intend for your application to be self-contained and not allow other applications to activate its activities, then you don't need any other intent filters. Only one activity should have the "main" action and "iaruncher" category, a8 in the previous example. Activities that you don't want to make available to other applications should have no intent filters and you can start them yourself using explicit intents (as iscuseed in the following section) ° However, if you want your activity to respond to implicit intents that are delivered from other opplications (and your own), then you must define additional inten filters for your etivity. er each type F202 Maer Pla. Opp va Trade Center eee vewsateciescom Page 17 » Sai Technologies Ph: 9052124499/6699 of intent to which you want to respond, you must include an clement and, optionally, a “category clement andor @ clement. These elements spevify the type of intent to which your activity can respond. For more information ahout how your activities can respond to invents, see the Intents. and Joes, Euers documteit. Stortiong wn sesvity ‘You can start another activity by callin startActivityi), passing it an Intent that describes the adtivity you ‘want to start, The intent specifies either the exact activity you want to start or dese: 3 the type of action you want to perform (and the system selects the approprisie activity for you, which « ven be from a different application). Aa intent enn also ceiry small amounts of data to be used by the activity that is santodh When worki inhin your own application, you'll often need te simply launch a known activity. Yeu can do so by © 19 ingeat that explicitly defines ds ss name. For ‘example, here's how one eetivity atarts another activity named Signln,Activity asent jtent — ew Inteut( this, Siznlaactivity class) staitActivity(inient), However, your application ini 1 also want to perforin soine action, such as Send ame sil, text message, or stares update, using data from your activity. In dhis case, your applicution might not have its own Activities to perform such actions, sv you cam instead levesave the activities provided by ether appiicattons ‘on the device, which can perform the actions for you. This is where intemis are really valuable—you ca: ‘create an intent that describes au action you want (o perform aud the system launches the appropriate activity ftom another application. 1f there are nuultiple activities that cau handle the intent, dhen de user ‘can select which one to use, For eximple, if you want (o allow the user 10 send an email message, you ean ‘create the following intent: Intent intent = new [ntent(Intent ACTION_SEND); {intent putki'ra(Intent EXTRA_EMAIL, reeipientArray), startActivityGintent); 4 202, Maleera Maza, Oop Aditya Trade Center, Ameervet ‘www sartechnos.com Page 18 » o uy ve Vee & Sai Technologies Ph: 9057174499/6699 The EXIRA,EMAIL extra added to the intent is a string aay of email addresses to which the email chould be sent. When én email application responds to this intent, it reads the string array provided in the ‘entra end places them in the "to" field of the email composition form. In this situation, the email application's activity starto und when the user is done, your activity resumes. Sua activity for a result Somecimes, you might Want 10 receive a resule front uh acivity by calling saAcuvireForksuh tin Subsequent activity, implement the ona stctivity dhat you start, In that case, start the cad of siertAcuvity(). fo then receive the result from the sivityResol() callback meld. Wher the subsequ activity is done, it retums a result in an fnvent to your on ActivityResul) aethed. For example, perhaps you want the user to pick one of their comtacis, so your ivity can go somet ‘wih the information in that contact. Here's how you can create such ai intent and handle the resutr: nate vord pie’Cantact) { 2/Ureate an intent to "pick" 2 contact, as defied by the content provider URI Intent inte jew Intent{ Intent ACTION, "CK, Contaets. CONTENT_URY} startAcivityForResultintent, PICK_CONTACT REQUEST): @oveniae: provected void onActivityResult(int requesiCode, int resu}iCode, intent data) { Af dhe vequest went well (OK) and the tequest was PICK_CONTACT_REQUEST if (resultCode == Activity. RESULT_OK && requesiCode = PICK_CONTACT_REQUEST) { 1 Perfor a query to the contact’s contemt provider for the comet's manne Cursor cursor ~ getComtentResolver().query(data.getData), stew Suing{] {Contacts.DISPLAY NAME}, ul], wull, ull, if (cursor.snoveTOFirst0) {/! True if dhe curser is wot empry inn volumphidex ~ cursor. yetColuumutden(Cuntacis. DISPLAY NAME), Suing sane ~ cursor. wetStrine(coluiuslider), 17 Do suinething with the selected contacts san } eS. £202. Najera Plaza Opp Miya Tene Conor. Ameo wesc Page 19 SaiTechnologies . Ph: 9052124499/6699 This example shows the basic logic you should use in your onActivityReswliO method in order to handle an activity result. The first condit'on checks whether the request was successful—if it was, then the resullCode will be RESUI-TOK—and whether the request to which this result is respond in this case, the requestCode matehes the second parameter sent with sta known— there the code handles the activity resnlt hy querying the ata returnes! in an fotont (he Anta parameter) ‘What happens is, a ContentReselver performs a query against a content provider, which return that allows the queried data to be read. For mor formation. see the Content Providers document For mére information about using intents, document Shusing Down an Activity You can shut down aa activity by calling is Amish metbod. You can aiso shut down 2 separate activity ng fnishciv that you previously started by ca Note: fa snost cases, yeu shawl not exphesly finch an semviy wsang hese metas. As disenssed inthe following seenig abv the aciily Mey, the Anetroid system manspes the hike of an actuary for you, so. yom dant need ta fnish your oven activihes. Calling these methods could adversely atteet the experted ser experience and should énly be sed when yon ahsnttely eno Want the er ty retary t this instance of the activity, Managing the Activity Lifecycle ‘Monaging the lifecycle of your activities by implementing callback methods is ervciel to developing a strong aod flexible application. The lifecycle of an activity ia directly affected by ite association with ‘other activites, ite tack and back etack. An activity can exist in essentially thice states Resued ‘The activity is in the foreground of the sercen and bas vser focus. (This tate is also sormctimes referred to 03 "runaing",) Paused ee 202s > lass Opp Ady Trade Contr Ameerpet. so tehaeecom Page 20 a ey 3 Sai Technologies Ph: 9052124499/6699 Another cotivity is in the foreground and has focus, but this one ill visible, That is, another ‘ctivity is visible on top of this one and that activity is partially wansparent or doesn't cover the cutive scrveu, A paused activity iy completely alive (die Astivity object is seained ia mncmuory, # twins all state and wieniber information, aud seamaiis atiaebed w the window re), but can be killed by dhe systern it eattenely low nsersory situations Steppedt ‘The activity és completely obscured by another activity (the activity is now in dhe "background’), A stopped activity is aiso still alive (the Activity object is rerained in memory, it maintains all state and member information, but is nor attached 10 the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere, IV 5m arty #6 pansed er slappes, the system can crop it fom memory either by asking it 49 fins (eating its Gnisht) method), oF simply killing its process. When the activity is opened again (afler being finished or killed), it must be created all over. Implementing the lifecycle callbacks ‘When. an activity transitions into and out of the different states described above, itis notified through variouis callback methods. All of the callback methods are hooks that you can override to do appropriate work when the state of your activity changes. The following skeleton activity includes each of the fundamental blecyele methods: public class ExampleActivity extends Activity { QOverriée public void onCreate(Bundle savedinstanceState) { super.onCreate(savedlnstanceState); 1 The activity is being created. } @Overriée protected void onStartQ) { euperoaStart(); The activity is about to become visible. } Override nnn 200, Majcra Pasa Opp Aditya Trade Center Amecrpet srr seteeioscom Page 21, Sai Technologies Ph: 9052124499/6699 protected void onResumet) { super onResumeQ) 1 The activity has become visible (itis now “resume”, Override proterter void onkunseQ) { super anPause) 1 Anovher activity is faking focus (Ihis activity ie about to he "pawsed") Civernide protected void ontop) { superonstep; 1 “The activity is na longer visle Gi is now *stopped") aersortide protected void aaDestrox0 £ super.onDestroy): 41 The activity is about to be destroyed. “Takei together, these methods define the entice lifecycle of an activity. By implementing these methorls, ‘you can monitor three nested loops in the activity lifecycle, = The entire lifetime of an activity happens between the’ call to onCreate() and the call to onDestrovl). Your activity should perform setup of "global" state (euch as defining Jayout) in onCreated), and release all remaining resources in onDestros(). For example, if jour activity has a thread nu ing in the background to download data from the network, it might create that thread in onCreate() and then stop the thread in onDestrov(. +The visible lifetime of an activity happens between the call to onStar‘) and the call to onStop(). During this time, the user.can see thé activity on-screen and interact with it. For example, ‘qnStop() is called when a new activity starts and this one is no longer visible. Between these two ‘methods, you can maintain resources that are needed to show the activity to the uscr. For example, you can register a Bron iver in gnStari() to monitor changes i impact your 1902, Mjears Plas, Opp Adi Tad Contr Amoompst ‘nv saherhnorcom Page 22 7OO09 ed eooccocecs

You might also like