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: When specifying required configurations be aware tat your upplication won't be inssulted un any device that does not have one of the combinations specified. Iu the abuve esumple a device wish a QIERTY kexboard ond a D-pad (but no touchscreen or trackball) would » ue be super ted Melly you sh ul develop sour applicution to ensure it works with auy input cunfigus tion, in which case ua vuses-configuration node is required, > usesefeature One of she advan of Android is the wide variery of hard:vare platforms it rans on \Use multiple uses-feature notes to specify exch will 1 hardware featnees your application requices. Us Jent your application frém being instaled! an a device that does ot snelide a reqpred hardware feature. You can require support for any hardware that 1s optional on a companhle device Currently optional hardware features include >> anelrond hardware camern K spptentions that vequise camera hardware > android hardvvare-camesa autofocus If you require an autofocus camera Ashe vaviey of platforms on which Andioid is available increases, su 10d will ihe uprional hardware. A full list of uses-feature hardware can be found here, You can also’ use the uses-foatuwe uode to specify he ‘mivimum version of OpenGL requized by your applicition. Use the glsVersion atsibute, specifying dhe OpenGL ES version as an integer. The higher 16 bits represent the majer number and the lower 16-bits represent the minor number, - > supports-sercens Alter the intial round of HVCA hardware, 2009 saw the intioduction of WGA atl QGP, screens to the Audioid devies menagerie, With fuwure Android devices likely to fearure devices with larger scicens, the supports-scicen uude Tels you specify the sureen sizes your application can, and can't, suypost Exact dimensions will vary depending on hardave, but iu yeuers! the supported Screen sizes match resolutions as follows: > smaltSereens Screens with a resolution stnaller than traditional HVGA—typically QVGA screens. >> normalSéreens Used to specify typical mobile phone screens of at least HVGA, including WGA andWQVGA. > lanyeSciccus Screens Jaryer tan uoriual. I this instance 4 large screen is considered to be significantly larger than a mobile phone display. a £202 spars la, Opp Aya Trade Ctr Anwar smashechvoscom Page 33 Sai Technologies Ph: 9052124a99/6699 > anyDeisity Set to true if your application ean be sealed to accommodate any screen resolution, AS of SDK 1.6 (API level 4), the default value for exch atuibute iy tue. Use thiy uote to specify sere sizes you do not support, opps caniain only one application nove I asesattribntes to spwrity the metadata for your application {including ite ttle, icon, and theme). During development vou should inclade a dlebuganble atribute set to trve to enable debugeing—though you may wish to disshle this on your release builds “The node also acts as a coaldiner that includes the Activity, Seevice, Coment Provider, and Broadcast Receiver tags used so specity the application compontnts, You can also define your own inyplementation ofthe Application eless, Later inthis chapter you'll lesen haww to create and use your owe Application class extension wo manage application state > activity An tag ie required for every Activity displayed by your application, Using the android:name attribute to specify the‘Activity class name. ‘You must include the main launch Activity and any other sercen vr dialog that can be displayed. Tryang to start an Activity that’s not defined in the me fest will throw a runtime exception. Each Activity node supports child tags that specify which Intents launch the Activity. andi oid label~"@stiingyapp name> {202 jer, Oy ya Trade Center, set sowsiechmascom Page 34 vey Sal Technologies Ph: 9052174499/6699 - > servive Ay with the activity tag, create a new service tag for cai Service class used application, Service tags also support ebild so allow late romtin service android:enabled=" ruc" android:name="MyService" provider Promdor lags specify each of your app 's Content Providers, Cantent Providers are sed to man database access and sh 1g within and bewoen applicatrons “provider android:permiscio 'com.paad. MY_PERMISSION" android:nam\ MyContentProvider" android:enabled="true" android:anthoritics ‘com.paad.myapp.MyContentPravider"> > receiver By adding a receiver tng, you can register a Broadcast Receiver without having to Taunch your application first, Broadsast Rees sd, will exeeute whenever a matching Intent ia brondeast by the system or an application, By registering Broadcast Reeciver in the manifest you can make thie proc centirely autonomone, If a matehi broadcast, your application will be started svtomatically and the registered Broadeast Receiver will be “receiver android:enabled="trne" andro label="My Intent Receiver” android:name=",MylntentReceiver"> > usce permission As part of the security model, usee-perm sion tage declare the permiscions you've determined your application needs to operate properly. Th 1¢ permissions you include will be presented to the user before installation commences, Permissions are required for many of the native Android services, particularly those with a cost or sccurity implication (auch es dialing, recciving SMS, er using the location-basd services) > permission Third-party applications cau alsy specify petissious before providing aucess Ww slated application components. Beftre you can restrict access to an application component, you need to define a ‘permission in the manifest. Use the permission tag to create a permission definition (0202, Majors Pana, Opp Ait Trae enter, Arorpot sew stchnos om Page 35 Sai Technologies Ph: $052124499/6699 Application components can then require permissions by adding the android:permission attribute. Uther applications will then need to include a uses-permission tag in their manifests to use these proisetei ‘components Within the permission tag, you can specify the level of aceess the permission will permit (nova, dangerous, signature, signatureOr$ystem),a label, and an extemal resource containing the description that espns the risks of he specified permission. co puad. DETONATE DEVICE" andr oilsprotectivaLevel="daugerous” andrvidslabel elf Destruct andr vid:leseriptivu—"@stringidetonate dese Iyer > instrumentation Instrumentation classes provide a test framework for your application compone rin time They provide hooks 10 manitor yone applic jon and its interaction with the system reseueres (Create a new nade for each of the fest classes you've created for your application “ > The ADT New Project Wizard aviomatically creates a new manifest fle when it creates a. new project. USING THE MANIFEST EDITOR “The ADT plug-in Includes a visual Manifest Editor so you don’t have 10 manipulate the underlying XML. directly. To use the Mauifest Editor in Eclipse right-click the AndroidMenifest.xml file in your project folder and select Open With Android Manifest Fitor. This presents the Andenid Manifest Overview screen, as shown in Figure 3-1. This sereen gives you a high-level view of your application structure, ‘enabling you to set your application version inlarmation and root level manifest codes, including - and , ab described previously inthis chapter. It also provides shoiteut Tinks to the Application, Permissions, Instrumentation, and raw XML sereens. Each of the next three tabs contains a visual interface for managing the application, security, and instrumentation (testing) settings, ‘while the last tag (asing the manifests file name) gives access to the raw XML. Of particular interest is the Application tab, chown in Figure 32. Use it to manage the application node and the application component hierarchy, where you specify the application components. ‘You ean specify an application’s attributes including its icon, label, and theme in the Application ‘202, Majeera Plaza, Opp Aaya Trade Center, Ameerpet ‘worwsatcechnos.com Page 36 oo: eoocoocecooce CcuevULUVUY & Sai Technologies Ph: 9052124499/6699 Atteibutes panel. The Application Nodes tree beneath it lets you manage the application components, including their atributes and any associated Intent Filter subnodes. ‘THE ANDROID APPLICATION LIFE CYCLE Unlike most traditional environments, Android applications have limited control over their own life cycles. Intead, application components must listen For chang accordingly, taki in the application state avid react articular eare 19 be prepared for untimely termination, By defaul, each Android application rons in its own process, each of which is running a separate instance of Dalvik. Memory and process. management is handled exclusively by the run'time, [Phile ir's uncorimen i's possible 1 force application ceriponents within the same agplcation to run ia differen processes oF to have muple applications shure the same process wsng the android process ane on the affected Component noes within the manifest Android aggressively manages is resources, doin lever it takes to ensure that the device remains responsive, This meane that processes (and their hosted applications) will be killed, without waning in ‘some cases, to free resources for higher-priovity applications generally thoce interacting directly's the user atthe time. The prioritization process is discussed in the next section ee EEEEEELLL #200. spar Paap Aya Trade oss, rere wen sacha Page 37, Sai lechnologies 1052124499/6699 8 Chapter 5: Intents 4 Helore you Cam hegin in interact with the phone intr, yon need to unersan the type of ete tt you wal nee todo the job Andro ees nts to da sprite jos within applications Once yon OD nose the us of Inlents, @ whe new world of appiation developmen! willhe open yews this secuan what an tncent is and hae alas use An Intent is Andrond’s method tor relaying ceria information from one Activity to another. An latent, hor terms, expresses to aAndvoid your teat to do semething. You ean think of se paseed between Activities. For example, assume that you have an Activity that needs #0 open a weh brostser sud display 2 page on your And device. Your Activity would send an “intent to spen x page in the web browser,” known a¢ 9 WEB_SEARCH_ACTION In to the Agdroid Injent Resolver, The Intent Resolver parses through ist of Acuvines and chooses the one that would to the web browser and starts the Web Browser Achvuy. Inte Oo best meth you nen; inthis ase, he Web raiser Actvty Phe tent ester then pases your page are broken up mt to ma categories | o ") Activity Action Intents Intents used to call Actwunes antside of your application Only one Activity’ n handle the Intent. For example, fora web browser, yon ner to open the Web Rrowser Acus:y 10 Q ? Broadcast Intents Intents that are sent ont for multiple Activities 10 handle An example at a Rrandeast 6 Intent woul be a message sent ont hy) Android afin the current hatlery level. Any Activity can proves oO ts Intent and reartarcontingly—for example, eancel an Activiiy if the hattery level i helnws a certain name of the Intent oes a good jah of describing what tat Intent does. ‘eis eon oe [pessoge Sen RCHS ATE EH betes Toons alas “ALAS AON [inl motes alo be dee ‘ReHeCAGH® eal Acie partescros | eexacion “TREC ALTON [Delon ewer AGATA (GELONTENTACTIN a 9 err ele pein tea O 202. aera Para, Up ava Trae ene, erst swontsnticnnescom Page 38 oo vvVe . UU weve Sai Technologies Ph: 9052124499/6699 Bonds nent |itessage Tegel sar (eee [ti ccasabin nerd “awouiaien GANDA [leds vent n eaed (UAT SUNY SITE GHANGEL ACTON [Tle dase a Fie TR RN a “The Intent ie only one-thied of the picture. An Intent is really juet chat, an intent to do eomething; an Intent cannot actually do amvahing by itself. You noed Intent Filters and Intent Receive (o listen for, and interpret, the Intents. Ap Intent Receiver is like the mailbox of an Activity, The Intent Receiver is ‘used to allow an Activity to receive the specified Intent. Using the previous web browser example, the Web Browser Actnty 18 Set up to verenve web browser Intents. A system ke this allows unrelated “Acts to gio lites tha they sna not he able 0 prorest tt algo allows Actisitig that need the ‘assistance of apother Activity to sitive that Activity withont needing to knows how to ral With ttents and Intent Receivers, ane Aciivity ean send ont an intent and annther can recewve i However, there needs to he somethiiy that governs the type of information shat ean he sent henween the two Activities. This is where Intent Filters come in, Intent Filters are used hy Activities to describe the types of Intents they want fo receive. viore importantly, they outline the type of data that should he passed ‘with the Intent. Therefore, in our example scenario, we want the web browser to open a web page. The Fnitent Filter would state that the data passed with the WEB_SEARCH_ACTION Intent shold be in the. form of a URL. In the next section, you will begin to use Intents 10 open and utilize the phone's disler. Using the Dialer Now that you know what an Intent i, itis time to see one in action. This section shows yon how 10 tase the DIAL_ACTION Intent to open the phone dialer. You will pass a telephone number with yonr Intent. If your application works co-rectly, you should see displayed in the dialer the mmher you pass with your Intent, ‘The frst step isto create a new projet for this Activity epee a 1202 Majeei Pans Opp ya Tad Ceven, Anew ae venwsdteimacen Page 39 Sal Technologies Ph: 9052124499/6699 Name the project AndroidPhoneDialer. The following illustration shows the New Android Project, wizard for this project, With your new application open in Eelipse, the first order of business ia to remove the TextView frei main.xml that contains that Hello World statement. The main.aml file should lock like this after you remove the Text View! <2yml version="1.0" encoding="ute8"2> “You need 1o add two new packages to your project to ntilize the DIAL_ACTION Intent, as follows, The first package allows yma to st up Intents and the second allows you to parse URIs. import android content. Intent; > import android net. Uri; or ‘There are several differsne Intent Filters an the DIAL_ACTION Intent that you ent use, You are using the Filter that lets you pass a phone number a3 @ URI, The nest step is to ercate your Intent. The ‘yniax for creating n Intent is 2 follow Intent ~ new Intent() For your application, replace the first parameter, “infont, ame, with Diallntent. To get the value for the second parameter, “tndroid_Intone, refer tothe list of Activity Actions in Table 7 1. You’ find that, to call the dioler, you need to use the DIAL_ACTION Intent. To call the Intent properly, use the format IntentDIAL_ ACTION. The last parameter, “, is the phone number. The DIML_ACTION Intent takes in data as 8 URI. Thus, you need to use Uri.parse to parce out your phone nember. Using Uriparse will ensure that the DIAL_ACTION Intent understands the number you'are trying to dial. You pass Usi.parse a string that represents the phone number you want to dial, "el:5551212" in this example. ‘The final call to create an Intent for your project should look like thi Intent Diallntent ~ new Intent(Intent.DIAL_ ACTION, Uri.parse("tel: 212"); ——— ‘#202, Majeera Plaza, Opp Adhya Trade Genter, Ameerpet ‘wwwsattechnos.com Page 40 @goooce: © ood uy 39 wy wuUU . Sai Technologies Ph: 9052124199/6699 me You use the notation tel:> Binally start the Activity °/ slartActivity{Diallntent) Placing a Calt from yur Activity this Secsion you wil Fearn what intent 10 add to your Activity when, calling the dialer. You witl also Jearn where to add your chosen Intent in the Activity"s code, Further, you vwill arn how to parse ihe intended phone number as @ URI. You need vo make a few changes to your code 19 move from te Dialer Activity 1 she Cal Activity. In this section, you are going tw edit your AndrolaPhoneDialer Activity (0 place 2 all ater open ne diater Adding the Intent to Your Activity You still need de Intent and Uri pucks those in place at the header of your AndroidPhoueDialer java fle. import android.comtent Intent import android.ne.Uris shown here~-s0 leave ‘These puckayes will euuble you to wot ouly instantiate te Latent dhat You néed, Lu also pass Une weeded Celepluonenuruber data 10 Ore tent (wit dhe Us puchoxe) or IL you ste flipping Uuvuxh die chapters wut of vider, aual did uot work on the project ia the previous sectivn, jinply Create a new project, name it AndioidPhoneDialer, aud add the previous two packayes 10 it, That will cately you up to speed. True to its name, the Intent that you need in your Activity is CALL ACTION. In much tie same way that DIAL ACTION opened the Andioid dialer, CALL_ACTION will launch dhe phone's valling provess aud initiate a call to the supplied suber To create the tatent, use dhe seine provedure as you did fur the dialer, uu Antent Callintent ts tne call CALL, ACTION. yew Intent(Inient.CALL_ACTION,Uri.parse("tel:5531212")); ‘Notive that you use Uri parse to pass a couectly parsed telephone muniber to the Avtivily. The next step is to tell Amid that you want to set dis Aeivity .e Ieuncl, und then luunel it, This is wecomplished using the following two lines of code, . ‘Callintent setLaunchFlaps(Intent.NEW_TASK_LAUNCH ); stortActivity(Caliintent); £120, Mera Plaza Op Ady Tne Conte, Anerpst vn satchnes com Page 42 a uy Sai Technologies s Ph: 9052124499/6699 Jn the frst tine, you sent the launch flag to NEW_TASK_LAUNCH. This launches 4 new insvance of the Call Activity Finally, you tell Android to start the Activity using your Intent, When finished, your AndrowiPhoneDaler java file should look like this, . package androxd_proprammers_guide AndroidPhoneDialer; Import android.app. Achuny, import androud.content Intent; import android os Kunde; inoport android. net Ui; public ciass AndcoidPhonefisler extends Activity ( 1° Called when the Activity i Fst created:*/ twUvernie phe vont anCreated Bundle icicle) { super ant reate(icieley setConrentView(R Jayout.main} /*° Create our Intent 10 call the device's Call Activity © {7° Pi the Call the number 5531212 */ nent Calliatent = new Insentoien, CALL_ACTION Uri purse 5351212"), 7 Use NEWETASK_ LAUNCH to launch the Call Activity * Caltintent ittaunchFlays(utest NEW: TASK LAUNCH); (7+ ially tit the Autivity *7 stantAutvityCallltens + Editing Activity Permissions Most Activity Action Intents fall into the category of requiring that the proper permission be set before Android will allow the action. As with many systems, Android just needs to make sure that only A jes with the correct exedentials be allowed to perform actions with Activities that are outside oftheir base. Here are the available permissions #202, Majeera Plaza, opp Aditya Trade Center, Armeer pet wornouitectnwsian Page 43 rechnologies Ph: 9052124499/6699 & ACHES ASSISTED GPS INTERNE SYSTEREMINDEAY ACUESS CLLL ID 2 RAISED TREAD PreHer NY ACCESS GS BRAD EDN EACIS, 2 ACLESS LOCATION READ FRADE BUPELK. ACIS, SUREAGR FLISGE I: RLSM fe BOOP CORPLEI AD BROAPEASL PACK AOL REMOLY RECEP 8 StF BROADCAST SHCKY BEN INSTRUMENT A HON Stat APPLIC EONS DeLttk Pack ces SIGSAL, PRARSIS HLS PROCESSES, pune SYSTIAL ALERE SuNDOW kL TASKS vociie serresas, Building the Activities Up tw now, you have created ealy sn Activity epplivarions. This is 10 say, you have created vai simplistic applications tbat encompass only ene “seen” of daa, Take a uninute, aad think of ae lst Few applications you have used. Chances are, they used more than one “window.” Most applications use amvliple windows to ther, display, andl save date. Your Android applications should be no different Although you have net yet leamed how to ercate multiple-Activity applications that run en Android, you got a hint about how to leverage multiple Activites in the last chapter. You used a new concept called JIntents to call—and ran—a core Android Activity, While the concept still holds truc inthis chapter, the exceution i lightly different when you want to call Activities that you have erceted, as opposed 10 calling core Android Activities, “The first thing you need to do is buitd the Activities. Then you can exeete the Intents thet will call them. ‘When building the Activites, you nced to follow a three-step process Intent code for the xml file 2 Intent code for the java file 2 Calling Activitics using an Intent ‘Once you create your first additional Activity, the rest should come very easily. NOTE ‘These steps arc uol bound to wack vibes. You vant per fina them in any order, tent Code for tne xml File Reanesnber thal all Andhuid Activities comprise Uuvee asin parts: Ue java fle that 4202, aera Pav. Opp Ao Trade Center. ere: swonsatechnoscom Page 44 oocoo 2o¢ oocooc Sai Technologies Ph: 9052124499/6699 contains the code, the anit file that holds the layout, and the package’s Manifest. To this point in the Luk, you have ouly used :nain.siul to control the layout ofa sinule Activity. However, tw tke alvantaye ofhaving multiple Activities, you must have wultiple .ssul layout files To crewte a uew .xui file, open your Eclipse project and mavivawe Wy the Pacha Uireciory, right-click te layout folder, and choose New } File Explorer, Open the res “The layout file is created, but itis emply. To vet dhe Activity oi ou the right four, aul de following code to west.xml, This cade will provide a base for your layout, If you need (a, you ean siinply copy dis code rom the exist mnain.xiul file ~2aml version es ~Linear Layout xminscandrotd="hup://schemas, 0" encoding= niirid.convaphiresiandrota” sandrold:orientation=" vertical” sandrvid:layout_widtt=" ‘androidstayor L_parent™ 2M" AIL parent+ “ILinearLasout> Invent Code forthe ja Tile Using the Package Explorer ayoin, navigate 10 the ste diestory, open it, and rightelick the sindroid_progronmers_euide. AndroidViewa package, as shown in he following iusuation. Once again, you are going to add a new file to the folder. AR you rightlick the AndroidViews package, sleet Now | Fite from the conte menu. This fle wit hot all the code forthe second Activity in his projoct Name the file testjava, You should row havea nice, new (but emply) java file, You jus need to add few lines of code to the file to make it usable: package textPackage eat ‘import android.app-Actvitys jnmport android.oe Bundle; public clace test extends Activity { 7 Called when the Activity i fiat eeate. @Override public void onCreate(Bundle cite) { super onCreateliciele seiContentView(R layout.test); J Thi is our Test Activity All code goes below */ } RE RE, 1202, Majecra laa Opp iy Trade Center Amerpet verorsakachnascom Page 15 Sai Technologies Ph: 9052124499/6699 Modifying the AndroidManifert.xml Open your AndroidManifectxm! file in Eclipse. ArdroilManifestsinl contains the global ceting: for your project. More importantly, AncroidMonifest.xml also contains the intent Filters for your project ‘The information that facilitates this process is kept in AndroidMznifest.xm NOTE Thy is only one AndroidNlanifest.sml fle per proj If your AndroidMonifest.xml file is currently open, it should appear os fellows: “action anéroid:name~"andraid.intent.action, MAIN” > eateyory android:name—"endrvie. intents intent filter activi ~ What you are looking at here is the Intent Filter for the An idViews Activity, the main Activity thet sos erented with the project. To this file you eon edd any’ ether Intent Fitters that you waat your prof handle. In this case, you want to sce! an Intent Filter thot wil handle the new Test etivity that you created. ‘The fallowing is the code for the Intent Filter that you need to add to the AndroidManifest.xml file: “action android:nam ‘android.intent.action. MAIN” > “category android:name=" android intent.category-LAUNCHER" /> ty> <2xml version="'1.0" encoding="utf 8"2> manifest xmlns:android~http:J/sehemas.android.com/apk/res/android. package-"android_programmers_guideAndroidViews"> “application android:icon~"@drawable/icon"> 20, Mae Pas Op ya Tad ese, Ane metescon Page 46 9 9 oO¢ eo oo »>oOocoocs Oo oo 3 we 2 1202, Majcer Pes, Opp Adis Trade Contr Amasrpst Sai Technologies Ph: 9052121199/6699 action ands oid:name="andyoid.intent action. MAIN" “intent-filer> activity activity android:name AutoComplete” anulruidslabel-" AutoComplete” action android:nam nrold.intent actor. MAIN" /> Scategory android:name="andrvid.intert.categor y, LAUNCH ~intent-filer slacdviiy Slayplication fechooscom Page 47 Sal Technologies Ph: 9057124499/6699 Chapter Tayouts 9 A Andi Ing i else tht handles aanging the way edn appeatan ihe serenn Ansthing that 8 8 View (or inherits from View) ean hr a child of # layout All of the layouts inherit fram Go Fayeut by ming cls that ines tram Viewbn. o Linear Laut RehutiveLave ‘VableLaveut oo0°e Apsolute Layout o Absolute Layout is based on the simple fea of placing each control at an absolute position. You specity = the exact x ap y coordinates on the screen for each control. This is not recommended for most UI development (in fact Absolute Layour is currently deprecated) since absolutely positioning every etement ‘on the screen makes an in‘lexible UI that is much more difficult 16 maintain, Consider what happens if a control leeds to be added! to the UL. You would have to change the position of every'single element that is shifted by the new contra ‘Here i a sample Tayont XMT. using Absolutel ayont ~ Button . android:id="@+id/backbutton” android:text="Back” > android:layout_x="10px" — SS android:layout_y-"Spx" a andridloyont_width-*wrap_conent” 1202 Mara Placa Op ay Teale ese Aner vests Page 48 caooocoocooce coo uVU wee Sai Technologies 1052124099/6699 android:layout_height="wrap_content" /> View android:leyout 10px" android:layout_y~"110px" andyeidhtent="Tirst Name’ andioid:layout width"vrap. content advoislayout height="wiap content” > FromeLayout can become more useful when elements are hiden and digplayed programmatically. You ccan use the attioute android-vieibility in the XML to hide specific elements, You ean eall seiVisibility Jom thé code to accomplish the same thing. The three available visibility values axe visible, invisible (Coes not display, but still takes up space in the layout), and gone (doos not display, and does not take ‘space in th layout). Cinearl ayont LinearLayout organizes elements along a single line, You specity whether that line 1s ve horizontal using androu-onentatinn Here ea sample I ayont XM. nsing I mearl ayour