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 Sai Technologies Ph: 9052124499/6699 UL, ond yurexisier it im onSwop) when the user ean wo longer see what you are displaying. The systeut might call onStart() aud onStap0 ulciple ines dating *he entie lifetime of the activity, as the activity aliernates between being visible wud hiddew w the user. The foreground lifetime of an activity happens between the call to uuRestanet) and the call 6 ‘onPausef). During this time, the activity is in fiont of all ther activites ws sencer and ras use input focus. An activicy can frequently munsition in ten! ue of de orewuund—For example, ‘onauset) is called when the device goes cw sleep oF sheen a dialog appears. Because this state eam transition offen, the code in these two oretheuls shiouid be feiihy Tighe inv wider wy avvidl stow transitions that inake the user wait Figne 1 inustrates inese loops and the paths an activity mig tke Het 0 ‘The rectangtes represest the callhack methods you can implement to perform operations when the activ between states. iy transitions 1202, Meera laa Opp Aya Trade Center meerpet vvsuchneacom Page 23 Sai Technologies Ph: 9057174499/6699 O° ey o Figure |. The activity lifecycle. The came feel callback nti vested in ble which eerie each ofthe catack mehodsin gy more detail and locates each one within the activity’s overall lifecycle, including whether the eyetem can ° lal the activity after the callback method completes, QO Sere rn rae nena een ——— Paget =O 5 ev vey a Sai Technologies Ph: 9052121499/6699 ‘Table 1. A summary of the activity lifecycle's callback methods. t i - Killable | Method ‘Description ! Next | ! ' after? | Colled when the activity i first created. This is where you should do’ all of your normal : static S81 up — create views, bind data to lists, and so on. This method is passed a Bundle aaa object containing the setivitys previous stare, NY Sut if that state was captured (See Saving Aciivity ‘State later. Always followed hy onStari() | ‘Called afier the activity has been stopped, just ronkestaml) — pmor wo it being stnted wy 2 No? oxStant) “Abways followed by unStartQ, fore the activity becomes visible — ' i ' vvaResanen| ‘onstar( i t Neo ‘Followed by onResume() if the activity comes ‘onStop) ho the foreground, ox onStop() if it becomes i i |bidden, | { { | Pe | | fiche wer. At this point the atv i at he | — [esrereeenem nn riee etl cnPause() i ho ie { | i | | ; | | iy |Alvays followed by onPouse) i t Co ee ee | Lemay amg acter scion “ths meted lye, ~ ‘en | I ypieay used to commit unsaved changes to} Honst0p0 { [persistent data, stop animations and other i 1202, Maer Mos Opp Ady Tad ener, Ameerpst seewasichnescom Page 25 Sai Technologies Ph: 9052124499/6699 Killable [Method Description i * after? | i Newt things that it should do whatever it does ve: because the next activity will not be rest hintit it emis, Followed either by onResume() if the activity ‘returns back to the front, or by onStop() if it becomes invisible to the user Called when the activity is no longer visible 10 the user. This may happen because it is being destroyed, oF because another acti either : nesta fan existing one or a new one) tus been. onSHt) Ye or my resumed and is covering i onDesiroy() Followed ether hy onRestart@ if the activity, is comming ack to ieract with the user, or by, loaDestroy() if this detivity is going away, | i I. ‘Called befire the autivity is destuyed. This is ‘tue fiual call that dhe activity will yeeeive, It) oe ati ii sei wy) | ifuishing (sourcone called finisi() on it), oF I Wes ~~ nothing this instance of the activity @ save space. You | joan dist iguish between these two scenarios | Dbccause the syste is temporauily destroying) ‘bith the isFinis'ingO method. ‘The column labeled "Killable after?" indicates whether or not the system can kal the process hosting the activity at any Bme after the method returns, without executing another line of the activity’: code. Three ‘methods are marked "yes": (onPausel), onStop(), and onDestroy(). Because onPause() is the firet of the three, once the activity is created, onPausel) isthe last method that’s guaranteed to be called before the pisces ca be kllod_if th sytem ust recover memory in an emergency, then gnSton end {4207 Mojera las Opp Adiga Tate Con Avert raw strhnncm Page 26 C Qo -ocagoaoa o > eeu uw Sai Technologies Ph: 9052124499/6699 onDestrayi) might not be called Therefore, yom shond nse onPanse() tn write erucial persistent data (euch 98 user edits) to storage, However, yon shone he selretive abot what information mst be retained during onPavse(), because any blecking procednres in this method hiock the transition to the next activity and slow the user expenence Methogds that ore marked "No" in the Killable column protect the process hosting the activity rom being lilled from the moment they are called. Thus, on activity i killable from the time onPause() retwens to the time onResumef} is called, It will not again be killable until snPausel) is again ealled and rerurns. Notes An activity tbat's not technically "Billable” by this definition in table 1 might stil be killed by the ‘system—but that would happen only in extreme circumstances when there is no other recourse. When an activity might be killed is discussed more in the Drovesses and Threading document ‘Saving activity state “The introduction to Managing the Activity Lifecycle briefly mentions that when an activity fs paused or stopped, the state of the activity i retained. This is true because the Activiey ebject is still eld i memory ‘when itis paused or stoppet—all information about its mevibers and current state iy still live. Thus, any changes the user wiade within the activity are retained iu msesmury, 99 that when the activity retuius wo the fureeruuitd (when it “resumes” chuse euauzes are still thee, sem | “Acitny restores ine user ‘Srenses i (Pie acer cama ‘ton fe cctye 122, Majeeca Maa Upp Asta trade Center, Ameerpet wow saeemnoscom Page 27 Sai Technologies Ph: 9052124499/6699 Figure 2. The two ways in which an activity returns to user focus with its state intact: either the activity is stopped, then restumed and the activity state remains intaes (let) oe the activity ie destroyed, then recreated andl the activity mnst restore the previous activity state (right). However, when the system destroys an activity in order to recover memory, the Aetivity object is destroyed, 90 the & em cannot simply resume it with it state intact, Instoad, the systany must reeren the Activity object if the ser navigates back to it. Yet, the user ig unaware that the aystem destroyed ti activity and recreated it and, thus, prabably expec the activity to be exacily as ie was. In this you can ensure, that important information abouy the activity state is preserved by implemeyting an additiona} eallback method that allows you to save information about the state of your activity nbé then restore it when the the system recreates the activity The callback method ia. whi gonSavelnstanceState(). The system calls this method before maki desvoyed and passes it » Dundle object. The Bundle is where you van stéee state infermation about the he activity vulnerable to bei sctivity as name-value pairs, using methods such as putSirin ‘Then, if the system kills your aetivity’s roces andthe user navigates back io your activity, the syst passes the Bundle to anCresteQ) 0 you ccan resiore the activity state you saved during onGavsInsianceStatel), If there is no state information 1 restore, then the Bundle passed to onCreatet) ull Note: There's aa wuarantee that onSavelasianceStaiel) will be called befere your activity is desuoved, Verause here ae vases in which it won't be necessary’ to save te state (Such as when the user eaves yout autivily using the BACK key, because the user is explicitly tlesing the activity). Ifthe methud is called, it is always called before gnStopi) and possibly before onPause( ‘However, even if you do nothing and do not implement onSavelnstanceState/, some of the activity stare is restored by the Activity class's default implementation of onSavelnstanceSiate(). Specifically. the default implementation calls onSavelnstanceState() for every. View in the layout, which allows each view to provide information about itself that should be saved. Almost every widget in the Android framework implements this method as appropriate, such that any visible changes to the UI are automatically saved ‘and restored when your activity is recreated. For example, the EditText widget saves any text entered by the user and the CheskBox widget savs whether it's checked or not. The only work required hy you is to provide a nniqne 1 (with the andeoid:id attribnte) for each widget you want to save its state. Wa widget fines not have an TT, then it cannot save its state 1202 aera sm Opp Aya Trade Cntr moet vwvnnsstachaoncons Page 28 u wuuuY Sai Technologies Ph: 9052124499/6699 “You can also explicitly stop a view in your layout from saving its state by setting the audraidsaveEnahled aribnte 40 "false" or hy calling the seiSaxeEnabledO methox!, Usually, you should not disable this, bt ‘you right if you want to restore the state of the activity Ul differently, Although the defoult implementation of onSaveinstanceSiated) saves useful information about activity’s Ul, you still might need to override i¢ to save additional information. For example, you might need to eave member values that changed during the activity’ life (which might corralate 10 values restored in the Ul, but the members that hold those UI values are not restored, by default), Because the defsult implementation of onSavelnstariceState() helpa save the state of the Ul, if you ‘oveiride the method i order to save additional state information, you should always call the superclass implementation of onSavelasianeeSterel) before doing any work, Note: Because onSavelustanceSiatel) is not guarantced 0 be called, you should usc it only 10 record the transient state of the activity (the state of the Ul} —you should never use it 19 store persistent data. Instead, you should use onPausel) to stere persistent data (such oy deta that should be seved to @ datuoase) when the user leaves the activity. A. good way to test your application's ability to restore its state is to simply rotate the device so that the ‘sczeen orientation changes. When the'sercen crientation changes, the system destroys and reercates the activity in order to apply altemative resources that might be available for the new orientation. For this reason alone, it's very important that your activity completcly restores ita state when it ie recreated, because users regularly rotate the sercen while using applications Handling coufiguratic anges Some device configurations can change during runtine (such as screen orientation, keyboard availability, and language), When such # change occurs, Android restarts the suing Activity (onDestroy() is called, followed immediately by onCreate(). The iestart behavior is designed to help your application adapt to new configurations by automatically reloading your application with dtermative resources that you've provided. If you design your activity to properly handte this event, it will be more resilient ro unexpected events in the activity lifecycle, The best way to handle a configuration change, such a¢ a change in the sereen orientation, 1s to simply preserve the siate of your application using onSavelnstanceStateQ) and anktestocelnsionceStatel) (or ‘ont reatel)), a5 discussed in the previgus section 1722, aera Pia opp aie Trade emer, Ames monesttnoscom Page 29 Sai Technologies Ph: 9052124499/6699 For a detailed discussion about configuration cha Uiem, read Handling Runtime Changes. that happen at runtime and how you should handle ‘Coordinating activities When on aectitity starts anuther, they both experience Ie tenasitions. Ube fst aciavay pases and stops (though, it wan't stap af 3 sbll visible an the background), whale the other actvaty ¢ ereated, ln case these activities share data saved to aise ar elsewhere, ws important to understand that the fist activity is not completely stopped before the second one is created. Rather, the process of stating the second one overlaps 0 th the process of stopping the first one ‘The onder of lifeeyele callbacks ia well defined, particulaily when the ovo activities are in the some B: sing the other. Here's the order of operations that occur when Activity tarts 1, Activity A's oaPause() method executes. 2. Activity Dis onCreateD, onStort{), and enlesumels methods exceute in seguenee, (Activity B now has user feous.) 3. Thea, if Activity A is no longer visible on 2ereen, its o=Stop{) method exeeuiss. ‘This predituble sequence of lifeurtte callbacks allows you to maui the Ueusiton of information fiom ne activity to amotls For example, if you must write to a database when the fst activity stops se that Ue following activity cou read it, then you should write to the database during vuStont, ooPaysel) instead of dusing 1202 oer ia Up Aya Trae Center Aner ven stectnes com Page 30 oooaoo0oos >eooococs Oao Oo 2 2 ee uur’ Sal Technologies Ph: 9052124499/6699 Chapter 4: Android Manifest Pile Buch Audiuid pruiect jucludes # uuuifest file? AudioidMauifestami, stored in the root of the project hierarchy, The wanifest lety you define the suuctae and metadata of your application, ies components, and its veguieurents, It includes nodes for each of the componienss (Acuvivies, Servives, Cuntem! Providers, wal Giowdust Receivers) that make up your application und, using kuweut Filters und Petwissivus, detenuives low they ‘interact with each other and with oxber applivativns ‘The manifest also offers ataibuws w specify application mews (ike ts fev u» dicane, aud ‘addirional top level notes can be used fur seeuiity setiinsy, unit tests, aud defining handwave aud platiinet Support requiremens, as described below. The manifest is wade up of a root tag with a package attribute set to the project's prckage. I andioid attribute that supplies sev Use the versiuuCuie atuibute to define the current application veision as an integer. This valuc is used inteinally to vompare application versions. Use the versionName amibute to sperify a public version siuinber that is displayed to users. ‘A typical maaifest node is shown in the following XML snippet manifest xmlnsiandroig~bitp://schemns.android.com/aplcreslandroid ‘package~"comm.my_domein.may_opp” android-versionCode="I" android:versionName="0.9 Beta”> = fos manifest nodes .} evant ‘The tag include nodes that define the application components, secority cettings, tes lasees, and requirements that make wp your aplication. The following list gives a summary of the available manifest node tage, and an XML snippet demonstrating how each one is wsed > usco-adk This node lets you define « minimum, maximom, and target SDK version that must be available on 2 device in order for your application to fi properly. Using @ combination of inSDK Version, maxSDK Version, and targetSDK Version attributes you can restrict which devices your application cau ua on, based on the SDK version supported by the installed platform. ‘The uiuinuin SDK veision specifies the lowest version of :he SDK thet includes the AP'Is you have used in your application, If you fail to specify « miniunom version one will be assumed and your application wil] Gash if it atteupts W access APIS that arent a ieble un the host device, a, aera Opp to Trae etn. eet vwwsatecioscon Page 31 Sai Technologies Ph: 9052124499/6699 “The maximum SDK version lets you define an upper Limit you ave willing te suppost. Your application will not be visible on the Market for devices running a higher platform release. 1's yood practice not to set the maximum SDK value woless you know your epplication will definitely not work on newer plaiforn eelenses, “The target SDK version at Seu tin ot SDF, version tells the stent that there is no need to apply any forwarder Dackward compatibility changee to support that particular version. ‘uses sik android:minSdi Versio andvoidstargerSdkVersion="5"> lunes ake The supported SDK version is not equivalent 10 the plaiforn version aie! casio be ceived foe it. Bor example, Android platform relea @ 2.0 supports the SDK version Siglo find the enrrest SDK versian for each plaiform use the table at > uses-configuration Use usca-configusation nodes to specify cach combination of inpat mechanisios supvoited by your application, You van specify any couibination of input devices tat incl, > reqFiveWayNav Specify te for this auribute if you require an input device capable of navigating vp, slowsn, left, nd right and of clicking the eurvent selection. This includes bath trackhalls and P-pads > reqHardK eyboard If your epplieation requires a hardware keyboard specify true > reqeyboardType Lets you specify the keyboard type as onc of nokeys, qwerty, twelvekey, oF undefined > reqiavigation Specify the atsibute value as ove of nonay, dpad, trackball, wheel, or undefined as a required navigation device Introducing the Application Manifest 1 53 > reqTouchScreen Sclect one of notouch, stylvs, finger, oF undefined to specify the required roucliscteen input. ‘You can specify multiple supported configurations, for example a device with a finger touchscreen, a trackball, and either a QUERTY or twelve-key hardware Keyboard, as shown here:

You might also like