Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
488 views
128 pages
Android Sai Tech PDF
Uploaded by
Vani Chowdary
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save ANDROID SAI TECH (2) (1).pdf For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
488 views
128 pages
Android Sai Tech PDF
Uploaded by
Vani Chowdary
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save ANDROID SAI TECH (2) (1).pdf For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save ANDROID SAI TECH (2) (1).pdf For Later
You are on page 1
/ 128
Search
Fullscreen
OYCOR AAD Sai Technologies Ph: 9052124499/6699 $ai Technologies #202, Manjeera Plaza, Opp Aditya Trade Center, Ameerpet, HYDERABAD 9652124499, 9052126699 www.saitecSai 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 2uo 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 3Sai 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 4J 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 5Sai 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 6ai 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 7Sai 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 8wu} 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 9Sai 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 asai 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 11Sai 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 0wy 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 13Sai 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 14Www 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 15Sai 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 ° eeooooveEvVvur 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 » ouy 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 19SaiTechnologies . 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 20a 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 eooccocecsSai 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 23Sai 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 5ev 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 25Sai 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 27Sai 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 28u 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 29Sai 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 Oo2 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 31Sai 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 33Sai 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 34vey 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 35Sai 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: eoocoocecooceCcuevULUVUY & 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 oovvVe . 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 39Sal 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: © ooduy 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 42a 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 43rechnologies 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¢ oocoocSai 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 15Sai 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 oo3 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 47Sal 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 coouVU 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
ext audioidid-"@*id/editLasiNanie” android. widti-"100px" android layout_widib"wrap_conten android tayout_height="wrap_comtent” android:layout_below="@ideditFirsiNanne™ android:layout_alignLet
androidsid="@+id/lastNere” androidetex! "Last Name” 00, aera ara, Uo atin Trae Lente Ameer ‘wsaiteemescom Page 54 opnoecomoooocogdneoooos ao.> ) vD Sai Technologies a Ph: 9052124499/6699 androidtlayout_width~"wrap_content” android:layout, ight ent” ondroid:layout_toLefOF"@id/editLaatName" andoidslayout_below~"@id/editFiratNomi "rap,
HeRow>
‘wrap_content” (>
kaise spdtoidwidth= "Ope ove nena ara Opp ara rage ete, Ameer enasntecanoscam Page 56 oO 9 8 ° S 8 9° a Q cootcooooceccSai Technologies Ph: 9052124499/6699 android-layout width=" wrap_content” androidlayout height*"wrap content J 2 ) Er 7202, Mejcera Pasa Opp Adi Trade Cents, Amecrpet sraitechaescom Page 57Sai Technologies Ph: 9052121199/6699 Chapter 7: User Interface Components Notifications + ° What are Notifications? The name itself implies their foncrionality. They are a way of wlening a wser ‘buat ait event that re needs 1 be inliunscd aboot or even take sense actin ou xen dat formation, oO oO o Notification on Audiuid can Le doue in any of the following ways? They are 1. ‘Vorst Nobheaton 2 Status Bar Notification 4 Dinlng Raves ‘Toast Notifications A toast notification is a message thnt pops up on the surface of the window. Ik only’ fills the amount off space required for the message and the user's current activity remains visible and interactive, The notification automatically fades in and out, and does not accept interaction events, Tinst, instantiate a Toast object with oné of the makeText() methotts. This method tukes tuce patsuneters, the application Context, the text message, and the duration for the toast. It retums » prove ititiced ‘Foast abject. You can display the tesst notification with show), as showa in the following example: Content coment ~ vetApplivationContend), ‘Chir Sequens text ~ "Hello twast!", jin duration ~ Toast LENGTH_SHORT: ‘Toast toast = ToastanakeText(context, text, duration), twastshow(): This example demonctrates everything yon need for most toast notifications, You should rarely need anything else. You may, however, want ta position the toast ditferentiy or even use your own layout instead of a simple text message. The following sections describe how you ean do these things. You can azo choin your methods and avoid holding onto the Toast object, lke this: ee ‘1201. Mera aa. Op Alga Trade Cem Aneeret vee sates com Page 58 eoagooovnvogoocaon0oonogoovo wcue weve Sai Technologies Ph: 9052124499/6699 Toast makeText(context, ext, duration) show: ° Positioning your Toust A standard toast nouitieation sppears near the holtom of the sereen, centered horizontally. You can change this position with the sef€ravuty(nt, mb snp) metho This accepts three parameters: a Gravity constant, ‘an x-position offset, and a y-posihan offset 2 For example, thie - you decide that the toast should appe, ip-left comer, you can set the gravity ke tuast.setGravity( Gravity. TOP|Gre: LEFT, 0, 0); Status Bar Notifivas ‘This Notification on Android can be done in any of the following ways. Status Bar Notification Vibrate Flesh jiaus OF Playa sound 7 Frou the Notification, you can allow the user to launch a new activity as well. Now we will look at status, ‘var totification as this can be easily tested om the crulator. To create a status bar notihestion, yo will need to use. two classes: Notification and NotificationManager LJ Notiheation = defines the properties of the stanis har notification like the ienn tn display, the test to display when the notification first appears on the stams har and the time to display CZ ——NotificationManager is an android system service that exerntes and manages sll notifieations, Hence you cannot create an instanre of the NotifiatinnManager but yon ean retrieve a reference to it By calling the getSystemNeruica() method cS -navz aera op aia ade ener, vornsechmescom Page 59Sai lechnologies 1U52124499/6699 ‘Once you procure this handle, you invoke the notify() method on it by passing the notification object created So far, you have all the information to display on the status bar, However, when the user clicks the notifiction jean on the s tus bar, what detailed information chould you show the user? Thie is yet 1o be created, This is done by calling the vethod set atestEventtnteg) on the notification ebject. Crenting a Nosificuiion A Notification object defines she details of the notification message that is displayed in the status bar end notifications window, and any other alert settings, such a5 sounds and blinking lights A status bar notification seiidies ail of the fol + Amicon for the srarus bar A title and messave, unless you define a custom notification layout A Pendinglment, 0 be fired when the notification is selected ‘Optional settings for the status bar notification inciude: + Aucker-text message for the status bar + Analest sound + Avirate setting + A flashing LED setting, ‘You can update the information in your stotus ber notification as events continue to occur in your ‘application. For example, when a new SMS text mesaage arrives before previous messages have been reed, the Messagisig application updetes the existing notification to display the total number of new rméssages received. This practice of updating on cxisting notification is much beter thon adding new notifications, because it avoids clutter in the notifiations window. Because each not ication is uniquely identified by the NovificationManager with an integer ID, you can revise the notification by calling setLatestEventinfo() with new vaiues, change some field values of the notification, and then call notify0 again. a ‘204, aveera Fiza, Upp Aditva ‘rade Center, Ameerzet ‘wwwsartechnos.com Page 60 oooo fo cecoecuoococaogeooo oooewuuvve Sai Technologies Ph: 9052124499/6699 “You can revise each proyerty with the ubject mmeimber fields (except fur the Co and the notification tile and text), You should stways revise the (ext 1 when you update the notification by calling sedlatestEventinfo() with new values for comensTitle and comtenrFext. Then call notifv() to update the notification, (Of course, if you've created a custom notfi n layout, then updating these title and text values has no effect.) Adding a sound You can alert the user with the default notification sound (which is defined by the user) or with a sound jed by your application ‘Ty ase the user's Uefault sound, add "DEFAULT SOUND" to the defaults fel notification defaults IF (tification. DEFAULT_SOUND; Adding vibration “You can alert she user with the the defgult vibration pattern ur will vibration pattern defined by youtt application, To ust the default pattern add DEFAULT. VIBRATE to the dof s fle notification detaults = Notteahon DEFAULT VIBRATE: Adding flashing lights Yo alert the user by flashing LED lighis, you can rmplement the detault hight patiern (if available), o letine your own color ancl pattern tor the lnghts. ‘To use the default light cotting, Add DEFAULT to the defaults fie: “notification defaults + Notification DEPAULT.LIGHITS; Dialog Boxes : 20%, Maja Fas Op iy Tue Ce, Amery res enumn Page 61Sai Technologies Ph: 9052124499/6699 A dialog is usually a small window that appears in front of the current Ac ty. The underlying Activity loses focus and the dialng accepts all user interaction. Dinloys are normally used For notifications that Should inierapt the user and to perform shout tasks that directly relate tn the anplieation in progress (sich AS a progress har or a login prompl) ‘The Dialox class is the base clase for erea Dialog directly. Inctead, you should tse one of the following eubelacces: 1g dialogs. However, you typically should not instantiare a AleiDiaiog |A dialog that can manage 2ero, one, bw, or three buttons, and/or a list of selectable items that esa include checkboxes or radio buttons. ‘The AlertLialog is capable of constr 1g most dialog user interfaces and is the svagested dialay type. See Creating an AlenDiglog below ProgiessDialox A dialog that dieploye a progress wheel or progress bar. Becaus DatePickerDialog A dialog that allows the user to select a date. See the Hello DatePicker tutorial ‘TimePickecDialog ‘A dialog thot allows the uscr to aciect a time. See the Hello TimePicker tutorial Tf you would like t¢ customize your owa dialog, you can extend the base Dialog abject oF any of the subclasses listed above and define a new layout. Sec the section on Creating a Custom Dialog below. Showing a Dialog ‘A dialog is always created and displayed as a part of an Achvity You should normally create dialogs from within your Activity’s onCeateDialoatint) callback method. When you use this callback, the Android system automatically manages the state of each dialog and hooks them to the Activity, effectively making it the "owner" of each dialog. As such, each dialog inherits certain properties from the “Activity. For example, when a dialog is opea, the Menu key reveals the options menu defined for the Activity and the volume keys modify the audio stream used by the Activity nr 120, Page 62 Plans Opp sey Tate Cots Ameerpet wornssitechocscom ooooso0 eoevooooode} eeuuvuere op Sai Technologies 5 Ph: 9052124499/6699 Note: If 1 deride to eveate a dining outs ofthe onCrenteDialag) methnd, it wil ot he atin 9 an Activity You ean, however, attach it ta an Activity wih sei ser Activity Activity) When you want to chow a dislg, coll showDialoplin) and pas it an integer that uniguely ideifie’ the dialog that you want to deploy. When a dialog is requested for the first ne, Andsoid calls onCresteDialow(int) from your Activity, which is where you should instantiate the Dialog. This eailback method is passed the same ID that you prssed to showDialoufint), Afier you ereute the Dialog, return the ubject at tae end of the method, ‘The best way to define the ouCrewleDialuxCius dud ouPiepareDinlextiul, Dialod) callback wets is with a swivch slatetieul that checks the A parameter that's passed inty the method. Lech case should check fur a unique dialog ID aud then create and define thé respective Dialog, For example, imazine wave Uhat uses two diffeient dialugs: oue tw indicate thatthe game has paused and another to indicate that Une gauuie ig uver, First, define an integer 1D for each dialog: static final int DIALOG_PAUSED_ID ~ 0: ‘Static fiual int DIALOG_GAMEOVER ID ~ ‘Then, define the onCreateDialogtinn callback with a switch case for each ID: protected Dialog onCreateliatogtint ie) Lialag dialog: switehtid) { cage DIALOG_PAUSED_I 11 do the work to define the pause Dialog break; case DIALOG_GAMEOVER_ID: 17 do the work to define the gaine over Dialog break; default: dialog = null; ) return dialog: y eet 1 20,saera ras, Op ava Tage enter Ancerpet wasaecnoscom Page 63,Sai Technologies Ph: 9052124499/6699 Note: In this example, there's no code inside the case statements because rocedure for defining your Dialog is outside the scope ef this section, See the section below about Creating an AlestDialow, offers code suitable for this example. ‘When irs time to show one of the dialogs, call showDignxGas) with the ID of dialog showDialog(DIALOG_PAUSED_ID); Dismissing 4 Dialog Wohea you're ready to close your dialog, you can, diem necessary, you can also call dismissDiatoa(int fs Dialog for you, by calling dismisc().on the Dialog object. 1f » the Activity, which effectively ealls dismissf) om the If you are using enCrsa nub to ami the state of your dialogs (es discussed in the pre) scction), thon every time your dialog is dismissed, the state of the Dialog objeet ia retoined by the Activity. H you decide thet you, will no long raced this object er it’s important that the state is eared, then you should call removeDialog(int). This will remove any intemal references to the object and if the ialog is showing, it will diomiss it . Creating an AteriDiulos, ° An AlenDialog is an esteusion of the Dialog class. 1k ig capable ef constructing most dialog user ‘interfaces and is the suguested dialog type. You should use it for dialoys dat use any of the following feawses: + Atine Atext message ‘+ One, two, or three buttons + A list of selectable items (with optional checkhoxes or radio buttons) To create an AlertDialog, use the AlerfDialog.Builder subclass. Get a Builder with AlertDialon.Builder(Context) and then use the class's public methods to define all of the AlertDislog properties. After you're done with the Builder, retrieve the AlertDialog object with create) ——— 4202. sera Poa. Opp Ais rade Ctr Ameer sew siehnescom Page 64 OQ om.ocore 0-2-02 3 euvue Sai Technologies Ph: 9052124499/6699 ‘The following topics show uw to define various properties of the AlenDialog usine the AlenDialog Builder class. If you use any uf the followin: sample code jinside your ouCreateDialoet calTback meitod, you can returu the resulting Dialuy ubjeut wy display the dialoy. Addipg buttons te an AlertDialog with side by side buttons like the one shown in the sereenchot to the right, use the cet. .Buttond) methods AlenDialog,Duildgr builder = new AlerDislog,Duilder( this) builder setMes "Are you sure you want co exit?") ) setP dsitiveButton("Yes", new Disloglnterfoce.C setCancelable( als ClickListener() { public yoid onClick(Dialoginterface dialog, int id) { MyActivity.this. finish) 3 DS} sethegativelutton("No”, new Dialoghnterface.OnClickListener() { public void onClick(Dialoglaterface dialog, int id) { dialog.concel(); 3 Mi AlenDialog alert = builder rede) Firat, add a mescage for the dialog with setMes age(CharSequence). Then, begin method chaining ond set the dialog to be no! cancelable (Go the user cannot cloze the dialog with the back button) with le(boclean). For each button, use one of the set.Button() methods, such as tPositivek con(), that accopts the name for the button oad a Dialoglnterface OnClick defines the action to take when the ser aclects the button that 1202 Maes Plata, Op ia ele Cee Auespe, wens Page 65Sai Technologies Ph: 9052124499/6699 Note: You can only edd one of each button type to the AlerwDialog. That is, you cannot have more than ‘ona "positive" button, This timits the number of possible buttons to three: positive, neutral, and negative, These names are (echnically irelevant 10 the actus] functionality of your buttons, bul should help you keep track of which one does what Adding a list ‘To create an AletDialog with alist of selectable items like the one shown to the right, use the setTzems() method: final CharSequencef) items ~ ("Ret "Gree", "Blue", AlenDial Builder builder ~ new AleuDialoy Builds (this), Duilder serTiile( "Pick a color"), builder serennfitens, n= Dialoslner fave. OuCliehListener() { public void onClick Diulusluter fave dial, int ite) ToostauaheT est ’ AvplivativuConteni), itemsfitem}. Toost LENGTIL SHORT) showt), ». AlenDialgg alert » builder.create(), First, add a title wo the dialog with setTitle(CharSequence), Then, add a fist of selectable items witht seiftems(), which accepts the wntay of iteins display und a Diuloghutes face. OnClickListener that defines the action to take when dhe user selects au ten Adding checkboxes and radio buttons “To create list of multiple-choice items (checkboxes) or single-choice stems (eadia buttons) inside the Gialog, use the setMultiChoiceltems() and setSingleChoiceltems() methods, respecuvely. If you create ‘one of these selectable lists in the onCreateDislog() callback method, Android manages the state of the ist for you. As long as the Activity is active, the dialog remembers the items that were previously selected, but when the user exits the Activity, the selection is lost Note: To save the selection when the user leaves or pauses the Activity, you must properly save and restore the setting throughout the activity lifecycle. Te permanently save the selections, even when the an ear sschccom Page 66 »Oo oOo >cooo eooce S 0 ia wo aoeSai Technologies Ph; 9052124499/6699 Activity process is completely shutdowrs, yo need in save the setlings with one of the Data Storage teebnuques > To create an Al Dialog with a Hit of si le choice items like the one shown tothe right, use the same ccode from the previous ex ile, but replace the eetlteme() method wit final CharScquencef] items {"Red, "Green", "Blue" AleswDialog.Builie: Uuilder = new AlentDialoy Builder ‘vuilde: setTitle"Pick a color"); nish uildes.serSingleChoiceltemstitems, Dial public voit onClick(DislogInterface dialog, 1, ne face, OnClickLiatenee() { ToostmakeText scaticnConteni(),itemafitem), Toast LENGTH SHORT) shot) Ds AlenDiulog « builder create() The second parameter in the set value for the cheokedirem, which indicates the zere-based list position of the defiult selected item. Use "1" to indicate that no item should be selected by default ProgeessDialog : A Brosressbi js an extension of the Ale jalog clasa thot can display a progress animation in the form of a spinning whecl, for a task with progress that’s undefined, or a progress bor, for a task that haa defined progrcasion. The dialog can also provide buttons, such os one to cancel a download, Opening a prowess dialog can be us simple as calling ProwsssDisluxstiow(), For exsuapl, the possess dialog shown w dhe right can be easily achigved without uisuaxiug the dislox though dhe auCeateDislowtin) callback, as shown ite, #202, Mateera Plana, Opp Aditya rade Center, ameerpet -wovwsaitechnos com Page 67Sai Technologies Ph; 9052124499/6699 ProgressLiialog dialog = ProgressLialog shaw(Myacuvaty ths," ‘Load Please want." nue}, ‘The first parameter is the application Contest, the second iso ttle for the dialog (left empty), the third is a nl nat patemetor #8 whether the progress is indeterminate (this ia only relevant when 4@ progress bar, which is discussod in the next section) ‘The default stvle uf'a prowess dialos iy the spins peel. If vou wun {u ereate a progress bar tbat shows the loading prowess with x lasity, sine mae cade io sequised, a9 diseunsed in the next section, Showing a progress har: Vo show the ssion with an animated progress har 1. Initialize the Pr sgreseDialog withthe class constructor, ProgressDinlos(Contest) 2. Set the progress style to "STYLE_HO! (int) and set any other properties, euch ae the message When you're ready to show the dialog, eall show) or rota the ProgressDialog from the oaCresteDialoufint) callback 4. You can inerement the amount of progress displayed in the ba by calling either setProgress(in vwith a value for the total percentage completed so far or inerementProgreesBu(int) with an incremental value to add to the total percentage completed so far For example, your cetup might look like this: ProgressDialog progressDialog; proggessDialog ~ new ProgessDialog(mmContext}, progressDialog.setProgressStyle(PyogressDislog STYLE HORIZONTAL): progressDinlog,setMessage("Losding..") prowessDialog,setCancelable( false); ‘The semup is simple, Most of the code needed 10 create a progress dialog is actually involved in the process that updates it. You might find that i's necessary to create a second thread in your application for this work and then report the progress back to the Activity’s 11 thread with a Handler ohject. If yon're not {familiar with using additional threads with n Handler, see the example Activity below that uses a sero Unread to inctement’a progress dialog managed hy the Activity 1202 Majeece Plz, Opp Ady Tene Comer Aerzt sevovsechneseam Page 68 Sy ' So oe eooodooort OD! G ©Sai Technologies Ph: 9052124499/6699 DatePickerDialog: ‘To provide a widget for selecting a date, use the atePicker widgs ‘ows the ser to geleet the month, day, ond year, ino familiar interface. Main xt: 1 encadting="uIf-8 "> Tinea aon xminscanleni grt/schemas anéroid convank’eesvanetoid’ ania layens_wi ‘wrap_santent™ ndrojd:layout_height="wrap cent” andoidiori io vertical">
updaweDisplay), ) ‘Vupiates the ime we digplay in the TextView privote void updateDispley() { snTinneDisplay.stText( now StringBuilder) sppend(ped(mHour)). append") appene{pedtmMinete))); private slate String padlinte) { if(e> 10) | tam StingvalueOfos 1 ete scturn "0" + String velucOffe); #202, Majeera Plaza, Opp adlays Trade Center, Ameer pec ‘wor alethnonsor Page 73Sai Technologies Ph: 9052124499/6699 ‘the callback received when the user "sets" the time in the dial private TimaPickerDiolog OnTimeSetListener mitimeSetLiatener ~ now TimePielierDial OnTimeSerListener() public void onimeGet(TimePicker view, int hourOfDay, ion minute) { rnflour ~ hourOiDay; Min yh; updos @Overide protected Dinlog onCreateDialogtint id} { cose TIME_DIALOG_ID. ronumn new TimePickerDialog( this, mifinmbeSetListener, mMour, mMinute, false) retura wll AutoCompletoText View: ‘An editable text view that shows completion suggestions automatically while the user is typing, The list ‘of suggestions is digplayed in a drop down menu from which the user con choose an item to replace the content of the edit box with. ‘The drop down can be dismissed at any time by pres the back key ot, if no item is selected in the drop Gown, by pressing the enter/dpad center Key.The fist uf sugeestions is Ublained from a data adapter and ‘appeats vuly afte a vive uuinber uf characters defined by die threshold Fxample: ‘Main.java: —— 19202 Majer Pas Opp Ada Trade Cantar, Ameopet ernecatochnsecom Page 74we Uw wu : Sai Technologies Ph: 9052124499/¢ public class min extends Activity { Override protected void onCreate(Bundlle savedinstances super. onCreate(savedinstanceStatey, setContentView(R layout maint: AutoCompleteext View textView > (AutoCompleteTextView) findViewByld(R Jd.autocomplere_counry: AmmayAdapter
adapter = new ArrayAdaptersString(this, R Jayout.ist_item, DISTRICTS): textView.setadaprer(adapter), stati final Suriny() DISTRICTS = uew Suiuel] { SRIKAKULAM™VUAY, ODAVARI' "KRISHNA" y GANAGARAM" "VISHAKAPATNAMTEASTGODAVARE SY 1G ain.xmi: <<7xml version="1.0" encooing="uf-5"2> ‘
~
.
Any good web designed knows how important the
element can,be. Ia a touch screen environment, like Android, where users often don't have a full Keyboard, like many Android phones, the ability to cimply select an item from a predetermined list ss absolutely vata. I's easier sor the weer to select winat they want «rather than have to types st protects your detabases from junk data’snd eypor by limiting choices to predetined, pre-screened responses. Ihe Andrond US has a very robust, user friendly wily way to handle this: the Andoad Spinner. and - relatively . programmer ft Spinners are simple to use, easy to program and just downright good looking. However, here are several Jifferont ways to poptlate the list of items in aa Android Spinner, and as ofthe writing of this article the Android Developer's Website (developer.android.com) only focuses on one of these methods. This article will break down both of the moat popular ways to do populate on Android Spiiner: with an array contained in your strings.xml file, ond from a database query. Then it will els0 demonstrate how to manually inses items into 9 spinner array using code. For ease of navigation, Tm placing each of these on a separaie page and including links te them so you can go to the page that best fits your needs as a developer. + Populate Android Spinner from string array resource 120 sjpra Pana Opp Adiya Trade Center Ameerpt veostehnee son Page 76 aoooosd oot2 Sai Technologies 5 Ph: 9052124499/6699 + Populate Android Spinner ftom database query (using a outset) + Populate Android Spinner wanvally with Java code Kxample: retin. ssl: ~ tml versio 10" encoding="s1f-$">
"planets_array'>
Mercuryssitern>
Venuss/item> a 17202, jets Pua Opp Miya Trade Cotes Ament ve stecscom Page 77Sai Technologies Ph: 9052124499/6699
LanbJitem> sitem>Maussiiiem> tear Tupiterssiven> iver Saurus iver Uramusssitem= oO Oo stringarray>
adapter = AmrayAdapter createFramResource( this, R array planets array, android. R.Jayout simple, spinner. jem): adapter.setDropDowe ViewResource(android R layout simple_spinner_dropdown_item) spinner setAdapter(adapter) public class MyCaltemSelectel istener implements OnltemSelectedlistener { Imihlie void onltemSelected( Adapter View<7> parent, View view, int pos, long id) 4 O26 O00 Voast make'Text(parent getContext(), "The planet is "+ parent geiltemAtPasition{pos) teString(), Toast. LENGTH _LONG) show() } co! ¢ & ee 202 sje Pan. Opp ys Trade Center. Ameerpet ‘we echnes com Page 78 & ©vevw. vevVuUeY & Sai Technologies Ph: 9052124199/6699 public void onNothingSelected Adapt: View parent) { 1 Do nothing. ) spinner setCnttemSelectedListener(new MyOntiemSelectedListener). Listy Andros provides ihe vig "ListView" which Is capable of displaying a scrollable list of items. ‘ListView gets the dain to display via an adapter, An alapter which must extend "BaseAdapter” ann is recponsitle for providing the daa model for the list and for converting the data into the fietds ut de ist. Android has two sta Word adapters, AvayAdapter and CursorAdapler . “ArrayAdapter” can bandlte data based on Arrays or Lists while “Simple nrsorAdapler” handle database related data, You can develop your own Adapter by extending these classes or the Basedaperelass.* ‘The following deseription will focus on ArmayAdapter and how 10 develop your own adapter. 11 will also give a small example tor "CirsorAdapter” Listctivity ‘You can dircelly uae the "ListView" in your layout as any other Ul component. In case your Activity is primary showing a list you can extend the activity "LictActivity" which simplifies the handling. "ListView". "ListActivity” extends "Activity" and provides simplified handling of liste. For example you shave a predefine method if someone clicks on a lit element, “ListActivity" contains a "ListAdapter” which is responaible for managing the data, This adapter must be set in the onCreate() method of your Activity via the method sctListA dapter(). Uf the user select in the lista list entry the method onListhteimClick0) will be called. This method allows to ‘access the selected element Android provides already sgme cefanlt layouts whieh you can use in your Adapter, eg. “android. Jayout.simple_list_ttemt”, In ease you dan want fo use one of the pre-defined layouts your re ave mace veomezatechnsason Page /9Sai Technologies Ph: 9052124499/6699 ‘own layout must have an element with the i¢-"@android:idvlist” which is the ListView. You ean also nse 8 view with the id "“@andeoickiVempty”. ‘This view is displayed if the list is empry. For example yor coil display here an error message ListViows and performance Displaying a lary dataset nist by etficienily implemented on a mobile devive. Therefore the ListView only creaies views (widget) ifnecd and sitach them to the view hierareby. The default Adapter ‘implementation for a ListView will reeyele views, eg. if a row is not dispizyed anysivre iwi Be recycled and only ils'content will change. If you implement your own adapter for a view you also shoutd do this to avoid performance problems. ‘This techigue will be demonswaved in this worl ListAcnivnty th AvvayAdapter sand Android standard layout Create a new Android project "de wogelfe andran! listarnivity" wth the aenvaty "MyList" You do noe need 10 change the datantt layoat “main emt Create the fotlawmng aetvity package ekeaitech.android.receiver; import android app ListActivity, import android.os Bundle; import android. view. Views ‘import android. widget. ArayAdapter; import android. widget ListView; import android. widget Toast; public class MyList extends ListActivity ( : 7 Called when the activity is first created. */ public void onCreate(Bundle icicle) ( uper.onCreate({eiels) . 17202, Mjur Pan, Opp Ada Tee Cntr Anew osaechnoe com Page 80 oO 8 8 3 oO ce g9oogcce GO ooowv oO Sai Technologies Ph: 9052124499/6699 1 Create an array of Strings: rhat will be pur 10 our ListAcrivity static Binal new Suring() { Swring{] DISTRICTS RIKAKULAM", VAY AGANAGARAM”,VISHAKAPATNAM™,"EASTGODAVARI’,"WESTG ODAVART, KRISHNA’ Creute un Arvay-ldapter, thas will actually make the Sirings above ‘appear in the ListView this set istadaprerfnew ArrayAdaptersSuing>Ciis, android. R.tayoutsiople_jist_item_1, DISTRICTS). override protected void onListiemCtick(ListView 1, ¥ wv. imt position, tog id) { per.ouListltemClick(. ¥, position, i), 4 Gee sve ive shat wus cliched Obices u~ this.wetListAdaptei() zetlteun(position);, Suing keyword = et0Siinet); Toast makeTeat(this, "You sélected: "| keyword, Teast. LENGTI_LONG) show): Léstsotivity with om layout “You can also define your own layout for the rows ond assign this layout to your row adapter. We will add 4 graphic to cach list entry. Crete the following layout file “rowlayoutwunl" iu the veslayvut folder of your project <1 ineatl ayont emingancroid= Itp:l/schemas.android.conwapkites/android” angdroid:tayout_width="wrap_content” andraid:layont_height="wrap_canient”> a #202, Moje las Opp Ais Tete Cees, Asi rman Page 81Sai Technologies Ph: 9052124499/6699 AlmageView android:id="@ lidlicon" andtoi “layout ie"wrap content” androidisren"@jdrawable/icon" android:layout width="22px" andiwidlayout maiyinTop="4ps" andioidlayout marginRivht '4ps" randroii Lesa etn View> “Ten View androidtext-"@*id/TextViewO1" apuivid.layout widim"asap_ comer’ android tavoun_cigh="s1ap_conicnn” waidsged id "G@Fid abel” androiditentsize~"30ps">iTen View SLinesrLayour (Change your activity "MyList™ o the fe2owing. This is almost the same coding as in me previous ‘example, the only difference is tat We ate using our own layout in the AtrayAdapter and teiing the adapter which U1 element should contains the vst package sk sarlech andlronl recenver mpart andeend app ListAcnyity: oaportanclroael as Hust: import intro view View: inypont android widget ArrayAdspter; import android widget 1 istView: Smport ai droid widget. Toast; public class Myli extends ListActivity { 1° Called when the activity is Fist created. */ ble void ontrente(Fundle icicle) ( super ontreateGeictey 11 Create an array of Strings, that will be put to our Listlctvity static final StringlJ DISTRICT yew String] { RIK AKULAM"s VAY AGANAGARAM"Y"VISHAKAPATNAM",EASTGODAVARD" "WESTG eee eee #202 Majer ara. Oo Ava Trade ere. Aneeet snsatennascom Page 82 coooocoooococoooec ood:Sai Technologies Ph; 9052124499/6699 ODAVARI,"KRISHNA™ 17 Lise yon ow layont anul point she aulapter to the Li elements which Ucomuiins the label Ue getListAdapter(new AnayAdapter
5 ~GridView sunlnsndroid—"upl schemas android com/aphreslandra” . | android:id—"@ridgrigview’ ‘android:layout_widii"Fill_parent” android:layout_height="fill_parent™ android:cotamnWidth="90dp" wu android:numColumns="auto_fi Sanna EEEEEEEEEemmeen eee eed nsec om Page 63 13202, Majeera ana, Opo Aditya Trade Cent Ameervet oySai Technologies Ph: 9052124499/6699 android vertieslSpaci "10dy" up CS ‘android:stretchMode—"eulunn Wid android horizontal pacio android: yravity="cen er Hetlogeid java: public Votd onCreare( Bundle savedInstanceState) { Oo HstanceSiate), Qa o on iper.onCreate(save setContentView(R.layout.nai GrislView gridview = (GridView) findView Bul id. sid sridview setAdaprertnew wten(ibisd uridview setOnkemClickListenes(uew OnlteuCYickListeuer() public wid usltemClick( Adapter View patent, View v, int position, long id) { ‘ToastnaheTeat(HelluGiidView.this, " | position, Teusi LENGTH SHORT).show() SG public class ImageAdapter extends BascAdapter { ° private Context mContext; o public ImageAdapter(Context e) { ° mContext = public int yetCount() { Ooo retuin wi Thunuiblds. ens, , o G 402, Majera Plaza Opp Aliya Trade Center Avwarpet ‘wor saitechnoscom Page 84 oO oC2 uw Sai Technologies Ph: 9052124499/6699 public Object getttem(int position) { return nll; public long getliemafint pasition) { retnen th 10 erente a new ImageView for each item referenced hy the Adan niblie View getViewdini position, View convertView, ViewGroup parent) { ImageView imageView: if (convertView wll) { Hf t's not veeyeled, initialize some ImageView = new ImageView(mContext) ures image View.seiLayourParams(new GridView. LayouParams($5. 859) Image View sexScaleTipetImayeView ScaleT ype. CENTER_CROPY, imayeView sePaddinu(3. 8.8. 8) Jelse { innageView ~ (huayeView) wonvertView imoge View setlmageResource(mThumbidslpesition)}, return imageViews I references to our images private Integer(} mThumblds ~ { Redrawable.sample. 2, R.drawable.sample_3 Redrawable.sample_4,Rdeawable.sample 5, Rdrawoble-somple 5» R.drawable. sample. i i Redrawable.somple_0, R-drowable.sample_1, | Redrawabie.sample_2, Rdrawable.sample_3, Redrawable.somple_4, R.drawable.sample_S, Redrawable-sample_ 6, R.drawable.samaple_7, Redrawable.sample_0, R.drewable.somple_, a E 202, Majors Paci Opp Aliya Trade Cees, Ames swmmsatedosant Page 85Sai Technologies Ph: 9052124499/6699 Rdiawable sample 2, Rdrawable.sample 3 Rucwoble-sauple 4, Rdiawablesimple 5, Rdiawablesauple 6, Rdrawable sample 7 Gantery Gallery is a layout widget used to display items in orizont selection at the center of the view, Feample iin aval
<1 ynenel ayo android! ‘rie inane ayo androidslayimt_widih="All_patent” android:tayout_heigat= ill_parent’ sinlbs:endroid="hitpy//schemas android convapkeres/an roid android:orientation= tical"
1202 Maera in. Opp Aya Trade Center Anse somsiehnoscom| Page 86Uw ue Sai Technologies Ph: 9052124499/6699
Gallery xample java pubhe class GialleryFxample extends Activity { private Gallery yaitery private ImageView imgView: private tnieger{] Lingid ~ { Ralawable.n 1, Rekawablea_2, Rerawablea_3, Rdrawables 4, Rdrawable.a_s, Jy @Override public void onCreate(Busidle savedinstanceState) { super. onl reotelsavedlinstancestarey seiContenView(R layout main) imgview AmageView)findViewBylU(R id. Jnaxe ViewO1), ingView setlinageResourcetlugial@); gallery = (Gallery) find ViewByld{R id.cxamplegallery); gallery.setAdapter(new AddlmgAdp(this)); gallery.setOnltemCliekd.istener(new OnltemClickListener() { public vord onltem(h-k( Adapter view parent, View v nt poston, lang i) { imgView setlmageResource(Imgid{position}}: » oY public class AddimgAdp extends BaseAdapter { int GalhemBg, 202, aera in, opp Ada Trade ae, Arp veto Page 87Sai Technologies Ph: 9052124499/6699 private Content cont, > public AddimyAdp(Context ¢) { Typodanvay typAtray~ obtaiaSiyled. Menbures{ sty leable, Gallery Theme) remy = typAray getRescurceld(R styleable GalleryTheme_android_galieryltemBackground, 0); typAmayzecyele(; publie int gown) retnen Img engin, Dblic Object getttemint position) { yewrn position; vubtic tn gettcoaia positon) { } public View getView{int postion, View convertView, ViewGroup porent) { IimageViews imgView = new ImageView(cont; img View setImageResouree(Imgidlpesition}; ting View setayontParams(new Gallery 1 ayontParams(80, 1) img View setSealeTypa(imageView SealeType FIT_XY) imgView setackgroundResource(Ceiltemg); return img View: tO Other Important Views In ANDROTD: a cr rd 202. jer Pa. Oop Aditya Trade Cente Amer wsatectoscon Page 68 oeces epmodcysd oa 0ww Sai Technologies Ph: 9052124499/6699 Bait Fest In this section, you will create a text field for user input, usin the EditText wis 4. Once test has been ‘entered into the field, the "Enter" key wil! display the text in a toast message. 1 Open the res layouviinain.amal file nnd add the Editiext clement (inside the Lis
2. To do something when the state is changed, edd the following ence to the end of the onCreatel nethod: final CheekBos checkbox « (CheckUox) findView Byhl(R.d.cheekbon); cheekbox.sct ‘OnClickListener(new OnClickListener() { public void onClick(View ¥) ( / Perform netion on clicks, depending on whether it's now checked if ((CheekBox) ¥}isCheekea())"{ ‘Toast makeText(HelloFormStuft.his, "Selected", Pons. LENGTH_SHORT) show(); J else { ‘Toast. makeText(HelloFormnStuft.this, "Not selected", Toast. LENGTH_SHORT) show(}; } } vy ‘This captures the CheckBox clement fiom the layout, then adds an View.OnClickListeues. The View.OuClickListeuer must inplemeut the ouClick(View) callback wed, which defines the action to be made when the checkbox is vlicked. When clicked, isChecked0 is called to check the new state of the check box, IF it hus been checked, then 8 Toast displays the message "Selected", comherwise it displays “Not selected”. Note that the View object that is passed in the onClick(View) callback must be cast ra CheckBox because the jsChecked method is not ‘202, Majera Pana Opp Adiga Trade Cemer Ameer ven sitecnoscomn Page 90 2 ° OoJ 3 3 wee oS Sai Technologies Ph: 9052124499/6699 ‘aéfined by the parent View class. The CheckBox handles its own state changes, so you only need to query the curvent state. 3. Runt Tip: If you need to chang: the state yourself (such as when loading a saved ¢ eekedthoolean) or togelel) method. heckBosPrelers Raul Busrars using the In this section, you will create ovo musvally-excluoive radiv buitons (enabling one disables dhe oiber), ativGroup and RadiuBuwon widgets. When eles radiv button is pressed, w tuast message will ve displayed. 1. Open the vesayounimain xml fle and adel wo RadiaBuwons. nested in a RagioGroup (inside tne Linear avout) Redotiroup android:tayout_widih="Gt1_parent” android:tayout_beight= ‘wiap_content” ndroid:orientation=" verical">
I's important that the RadioBurtons are grouped together by the RadioGroup element so that no ‘more than one can be selected at a time. This logic is automatically handled by the Android system. When one RadioBuston within a group is selected, al others are automatically deselected. le Center, Aneerpet ssaechnoncont Page 91Sai Technologies ws2124494/6b99 ‘To do something when cach RadioButton is selected, you need an View, OnCliekListener. In this ease, You want the listener to be re-usable, so add the followin the IelloPormStuff Activity code to ereate a new member in private OnCtiekt istener radic_tistener = new OnCitekList, rer) ¢ public vote onClick(View vy) { Hf Perform action on clicks Radiaution r= (RadioButton) ¥: ‘Toast make Text(ifelloFormStuffthis, 16.getText0, Toast ENGTH_SHORT) show); Hirst the View that is passed co the anfhek{ View) method ise LLoast message displays the selected radia bustton’s text 3. Now, at the bottom of the anCrgatel) method, add the followin final RadioButton rodio_red~ (RadioButton) find ViewBylO(R id redio_ red * final RadioButton rodio_ blue ~ (RadioButton) find ViewBylU(R id-ratio_ blue); radig_red.selOnClickl istener(radio_ listener); Fadiosblue.setOnClickListener(radio_listener)s captures each of the RadioDutions from the layout and adds the newly-created View, OnClickListener to each, 4, Ruf the application, ip: If yon need to change the state yourself (such as when loading a saved CheckBoxPreference), nse the setCherked(hnalean) or togale() method. Toggle Button In this section, youll ereate 2 button used specifically for toggling between two states, using the TogaleButton widget. This widget is an excellent alternative to radio buttons if you have two simple states that are umutually exclusive (Yon and "off", for example). ‘Open the res/layoutimain.xml file and add the TogeleBulton element (inside the LinearLayau): 1202 Maier aa Op Aya Trade enter, merpt sae oscom Page 92 G ° a ecooooSai Technologies Ph: 9052124499/6699 ‘
3. Sun the apsieation. 2 ip: If you need to change the state yourself (such as when loading a saved CheckBoxPreference), use he setChecked{boslesn) oF togale() method. a 2) 20m mace is, opp nara comer Ameen vwresanecmoscom Page 93Sai Technologies Ph: 9052124499/6699 Rating Bar Iu this section, you'll create a widget that allows the user to provide a rating, with t |. Open the res/layout/main.xml fite and add the ReiingBar element (inside the Linear ayous androidilayout_beig andyoid:numStass="5" androidistepSize=! one The android:numStars attribute defin how many stars 10 dieplay for the satin android:stepSie attribute defines the gronulavity for each star (for example, a velue of 0.5 would allow half star ratings). Todo sone enCreatet) method ssn set, aul the following code wo the ond of the final RatimeBar ravineban ~ Ra a1) fasd View yldl(R iuLsatingbor}, ratiugbar se1OnRatinyBay ChungeListeues (new OuRatineBarChangeListencs() { public void ouRatinyCluuved(RatiueBar catingDat, float cating, boolean FromUser) { ‘Toast.nakeTent(HelloFormStuffthis, "New Rating: * ! rating, Tuas LENGTH SHORT) show(): Ds ‘This captures the RatingBar widget from the layout with FindViewByld(int) aud dieu sets ai RatingBar OnRatingBarChangeListener. The onRatingChanyed() callback method then defines the action to perform when the user sets a rating. In this case, a simple Toast message displays the new rating. 3. Run the application. rt 19202, Maeera az, opp aya Trade center, Ameerpet wovwsaltenuseomt Page 94 3 8 So °° omy o céo eoocdvpocooceSai Technologies Ph: 9052124499/6699 Services : What is Service? A scrvice ic 8 component which rune in the background, without interacting with the user. The Android platform provides a lot of pre-defined serviees, usually exposed via a Manager clas. In your activity you access corvices via the method gerSystemService(), Own § ‘They sun the main thread of theit proceis. Thereforé you shoud 1 performance intensive tasks in the background Ovn Serviees: ‘You can declare your own service 10 perform Jong running operations withous user interaction oF 10 supply functionality vo ocker applications. A activity Start a service Via the starService() method and stop the service vie tite stopService() method. If the activity wan! w interact with the service it can use dhe bindServive() method of the service, This requires an "SeriveComection” object which allows 10 ‘eounvet 1 the sesvive cand which vou a [Binder ebjeut. This IBiader object caus be used by the utisity to comununicate wit the service. Once a service is started its onCreate() method is called.” A erwaids the onStanCommand() is called with the Intent dat provided by die activity. stuntService also allows to provide a fag with determines the lifecycle beluavior uf the servizes. START STICKY is used fur services which ure explicit started or stupoed. Servives stunted with START.NOT STICKY will cud aulo:aiically after dhe vuStartCommand() wiedied iy done” A sevvive is seated widin the udu Uuead of the upplivation therefore all long eunuing tasks should be pesformed in the backerouud A. Services needs 10 be declared in the *AndroidManifes.xml" via a
and the implementing class must extend the class “Service” or ‘one ofits subclasses. ‘Cine common ease is that the service and the gctivily are very closely related. In this case class just case the [Binder to the clase the service provides. See Local Service Example for an example Another example would be the usage of Remote Messenger Service. In this case activities ean send ‘mesoages to the service and receive mescages as well if they register for them, a 11202 Maia Psa Op ya Tee Crier, Ameer venison Page 95Sai Technologies: Ph; 9052124499/6699 Broadeast Receiver: A broadcast receiver is @ elasa whieh extends "BroadeasiReceiver" and which is registered aso receiver in ‘nn Android Application via the AndroidManifest xm! (or vin code). This class will be able to reecive intents vin the sendBroadeast() method. "Broad cccivee" defines the method "onReesive()". Only wg this method your brondeast rcesiver ebjeet will be valid, aflerwords the Android system svill consiter your object as no longer sstive, Thereli sou cannot perform any asynchronous operasien Pending ment: wilt also use a Pend yinient, \ Pendingintent is a token that you give to another application (eg. Notifiearinn Manager Alon Manager or over J party applications), which allows this osher va to use te pe sions af your application to execute a predefined piece of code ‘To perform a broadcast via a pending sntent sp 4 Pendingintent via Pendingintent getbimnsdeast(). To perform an activity via an pendinu:yntent yon reserve the actvaty via Penchagintan Acwvityt) Broadcast Receiver Example: ‘We will define « brosdeast receiver which listens to telephone state ch ygeo. If the phone receives a phone call then our receiver will be notified ond log a message. Cale a ew pioject "de.vogella.andraiducceiverphone”. We do not need an activity fullowing "AndsoidManifest” Create the ‘<2xml version="1.0" encoding="uif-8"?> “
receiver android:name="MyPhoneReceiver”> -
(WOrerride public wad anktereive(omtext contest, fate! itn) { Findle extras = intent getFxtrast) it( tag * null) String state = extras.getString{ TelephonyManager.EXTRA_STATE): Log.w("DEBUG", state); if (state equals( Telephony Manager EXTRA, STATE_RINGING)) { Suing phoneNumber = extras sgetString(TelephonyManager.EXTRA_INCOMING_NUMBER): Log.w("DEBUG", phoneNumnber), ‘Tf yon install ygpr application and receive a cal, e.g simulated by the DPMS perspective in Relipse, then ‘your receiver will he called and lata message to the console. eee #202 Majera aa. Opp Adiga Trade Castes. Ameepet hecho com Page 97‘Sai Technologies Ph: 9052124499/6699 tens ‘Menus are ant important pat of au tivity’ user imerfsve, which ovide users a familar way 1 perform aeons, Rndioid offers # simple framework for you to add standard menus to your application. Tho as thse types wf epplisation Options Mena The primary collection af’ menu iteme for sn aeteity. which appears when the a touches she MENU button. When your application is running on Andro 2 oF later, you can provide quick access to select ‘ncn items by placing then ditecty it the Action Dar, as "action ite [Contest Menu A floating fst oF meni ems that appears when the user provide context men, Submenn A floating let of men item that appaare when the wser tayehes 9 menu item that cowtains 9:nesed snem ‘This document shows yon haw 10 create exch espe of monn wwiny VME to define the content af the mens ad callback methods in your activity to respond when the user (Creating a Menu Resource Twsieal of instuntiating a Meu in your application code, you should define « meise and all its ites jv any XML _meou resource, thon inflate the menu resource (load it se a programmable object) in your application code. Using a ‘menu eesnwrce ta define your meni 6 a good practice hrealse Mt separates the content tor the meni traey yowe ‘aplication code. I's also easier co visualize the structure and eentent of @ menu in XM ‘To create a menu reswuree, create wt XML file inside your projets ves/urenu/ directory and build Ure menu with se following clemenis Defines 2 Menu, which is» container for ment items, A
element mast he the root node for the file ‘and can hold one or more
and
elements. Creates « Manultem, which represents a single item in a menu. Thie element may contain a nested “menu> clernent in order to crestea submeny.
‘An optional, invisible container (or “item> elements, I alluss yuu w ealeyurize my items so they share properies such as active state snd visibility, See the section about Menu groups ‘707, aoe laa Opp Aya Tex Coro. ert sean cainehscom Page 98 c0O0 acco a o @eoooce £ Qo c2 Sai Technologies 1052124199/6699 Here's an example menu named game_mienu xm -<2am version="1.0" encoding~"uth ‘ine noslnssandoid="hitp:echemac.android.comaaphireandroid™> items andenidce"@udinew_ game" asciditle="@stingne Griacip® (arawablevie tel citer andro andoiiee angroidsitle="@sui Smo ‘This example defines a mene with i009 items. B the teres sudroidia A resource ID tha's unique tothe item, which allows the application can recognize the item wnen the user scleusi andieidicos A reterence o a drawable 19 use asthe ems eon, caudvoittile Arofetence tos string to wee asthe item's tile, “There are many more attributes you ean include in an citem>, including some that spesify how the tem may appear sn the Action Bat. For more mformatton about the XML syntax and attributes for a menu resource, See the Alea ‘Resoutee reference, lads ia Menu Resource ‘From your application code, you an inflate a menu resourse (convert the XML resource into © programmable object) using Menulaflaterinflate(). For example, the following code inflates the game_mena.xml file defined ‘above, during the onCreateUptionsMenul) callback method, to use the menu as the actvity’s Uptions Menu: @override public boolean on icatcOptionsMenu(Menu menu) { Menulafaterinfster~ getMenutafte)s Jnflsterinftat(Rmenu grme_mend, mens) return trie: 17202 Maja Op Aya Tad ener, cejt senses Page 99Sai Technologies Ph: $052124499/6699 “The gatManulaflater) method returns Menulnflaer forthe seivity. With this abject, you can call inflate). whieh inflates a menu resource info @ Menu objec. In this example. the menu resoutee defined by yame_meniaimi is (hed imo the neu that was yasse in unCrewte- Options feu). (This calibat meed for de Options Menu is discussed more in the nest section) Creating an Options Mena ‘Vhe Options Msn is whore you should include basic ativty actions ands igotion items (Far example, a acoessible in wo distinet ways: the MENU: Toucan 19 openythe app Tienion senings). Heme in the Optiaws Mow ve jon oF in dhe Action Sar (on devices running Andveid 3.0 er ighen . When running on a device with Android 2.3 ang lower. he Options Menu appears at the Bottom of the sereen. as show in Agu b. When opened, the fist visible poston of the Options Menu isthe icon menu. It holds the fst sin menu items, Hy add more than vis ikem to the Options Menu, Andeoid plaees the sixth item and those oer it which fhe user ean open by touching the "More" menu elem, (On Android 3.0 big. tems from the Options’Menu is placed in the Action Bar, which appears atthe top of ie ucsivty it lave of uve Waditivnal Gite bas, By default all tears fiom dhe Options Mew are placed in the oo men, whieh the wer ean epest by 1ouchis he mony icon om the right side ofthe Action Bar, However yew ean place select avon items creel sn the Action Hara “action tein, lor ansian access, arshovwn in gure 7 When the Aidroid system creates, the Uplions Menu for the fist time, it. calls. your actvity’s 1CueueOpionMenu( weiod. Oveide this mesbod iu jowr vetiviyy sud populate the Meus that i pessed iuuy the ‘method, Mona by inflating a menu recource a¢ deseribed sbove in Inflating a Manu Resource. For example: GOverride [Pole honlean ont realeUptions Menu Mens mens) { Menunfiater indlaxer = yedMenutntlaverQ inflate nflate(R.aenugome_meuu, menu); “You can also populate the ment in bode, using ade to add items to the Menu, ‘Note: On Android 2.3 and lower, the system calls onCreateOptionsMfenu() to create the Options Menu when the ‘uses open it For the Fist Gite, bu on Andiuid 3.0 aid greater the system creates it as sun as the aetsity is cated, in order to populate the Action Bor. Responding to user action 11202 Mafeers Pass Opp Aliya Tole Conte, Anceye sroveadtedossin Page 100 obptboood eos= re] VUVYe Sai Technologies Ph: 9052124499/6699 When the user selects a menu item from the Options Menu (including aetion items in the Action Bat), the system calle your ativity’s eaOptionsTiemSeectiQ) metod. his method pases the Menulten thatthe usr selected. You can identify the menu item by calling Becker), which reves the unique AD for dhe mem ier defined by the sndioidd wtsibute in dhe atens resouice oF with an Foteger given to the add) method). You ean mateh thi 1D gains known menu items aed perform the appropriate setion, For example @Orerride ppoblie bolas nnCptinnshemselected( Menem se) { +H Hhale tsi selection ‘witch (teat getterntd() { cove Ridinew_ game: sewtamel: dhe showHelpQ fault eter super onOptionstemSelnesed( tem) Tn this exuenple, goltemldQ queries 8 agsine! the rrsnweee Is that were assigned to menu ems yn the XML. resource. When a swrteh case successtly handles the menu item, it retwens true 10 i 1B forthe celeted menu ite and the ewte itsioment compares the ID leave that the Tein seletion was hndled, Otheiwise, the defsult Sstatejient passes the menu item to the super class, in case it ean handle the item selected. (IF you've directly ‘axtended the Aétiuty class, then the super class retorne Fee, but i's a gond practien ta pace wrhandled ments items to the superclass instead of directly returning false.) ‘A.ditionally, Android 3.0 adds the abibty for you 10 define the on-click behavior for @ menu item jn the mens ‘resuunes XML, using the androidionClick tribute. So you don't need to implement enOptiansliemelested(), Using the andioid:onClick attribute, you can epecify 4 method to call when the usec seats the menu lem. Your antviy ‘rst then implement the method specified in the android:onClick attribute so'that it accepts @ single Menultem ‘Darametet—when the system calls this metho it pases te menu tem selected. wh Ff your application conuins mukiple activities nd sowie of dhem provide dhe suine Options Mewu, consider ‘cacating an activity thet implements nothing except the onCresteOptionsMenv() and onOptionsltemSelested/) ‘methods, Then extend this class for exch activity that should share the same Options Menu, This way, you have to ‘manage only one set of code fr hanling meno actions ad each descendant cass inhenits the meno behaviors NT 19202, Msjeera Plas Opp Adiga ade Centar Amery, smawastachncecom Page 101Sai Technologies PI 1052124499/6699 1 you want iy ald menu items Wo one of your descendact activites, override enCevateOprions¥enut) in thee activity Call super.oaCreateOption fenu{mesu) £0 the original mews items are ted, then add new menu items with menuaddl), Yow enn alsa oveeride the super elases behavior fr diva menu eas Changing menu items at rontione Once the activity is evra, she onteesteCpinasMeni method 1 ‘keeps and seaises the Meni you define in hi led only once, as deseribed above, the system js mecha! unl your aetivty fs desituses. yon want se change the ‘Optivns Mess any thine after is fest created, you must override the gePrepar’OntionsMenu(} method. This pastes you the Men objet ait erent eins, Thi itl if youd lik to remove a diab enable meu iene de pending on the current sate of your application. (On Andtond 2.5 and lower, the system calls onPrepareDptions Mevut) each time the user opens the Options Menu, ©n Android 3.0 and h ‘You must call invalidateOprions enuf) wher You wancio update the Eau, the snvens is always open. The system will then call onPsepareOptions\enul co you van update the menu item Bote: You should never thange items in the Options Momu baced on the View curently ix focus. When in t imiode (when the user ie not using a warkball or apna), views eannor take thes, <0 yon hold naver ice ews a6 Pe basis for modifying items in the Options Mena. If you want co provide menu items that are context-sensitive (0 a View, use a Comest Menu. 1f youte developing for Android 3.0 or higher, be sure te also read the Action Bar developer guide Creating a Content Mens ‘A content mena is concsptuslly snsilar ta the menu displayed whan the user performs 2 ight-lich" on a PC. You should use a context ment to provide the user seeess to actions that pertain fo a specitic Hem in the user interlace. ‘On Android, a content ménu is displayed when the user pesfurms a “long press” (pres und huld) on a tein ‘Yo can oreate a context menu for any View, shouyl couteat sneuus ave most vften used fur items in & ListView. ‘Whe the user performs a long-press on an item in a ListView and the list is registered to provide a context menu, the list item signals to the ucer that a context mem available by animating its background color—it transitions ‘rem orange ta white hetore opening the context menu. (The Contacts application demonstrates this feature.) Register a ListView . — 1202 Majer Pas Opp Aliya Tada Centar Armeepet, sr eechacecom Page 107 oO 8 9 5 3 Go 6 Oo booo0c cofooeSai Technologies Ph: 9052124499/6699 1 your activity usesa ListView and you want all lis items 10 provide a context menu, register all items for a context rich by passing the ListView to euisteePoxConte tDfens() For example, if you'ousing a Lis Activity, register all list tema like thie resinerForContentMeno(getList Views In order for View to provide a camtest menu, you! munt "register" the sow Fura contest menu. Call veistertnuUontestMfennt) ant ass the sew you Want fo give a context mens, When this View then reeenves a ress, 1k displays content sen “To tine the cumiext mete’ appearance and UuleviuL, eecusidc your activty’s Louteat wucu eBaech aad, saCrcarsContesthMenul) and an Contestliem Selected). For example, her's sn onCreateContentMenul) that uses th ext_stenu.venl menu resource: GOvervide public void onCreateContextMenn(ContentMenu menu. View ContestMenulnfe nenslnfo) { euperonCreneCdntentMenu(meng, % menala fo) ‘Menulntiaer anttater = getMenulntater infave Mao{Rnens.costent_wenu, sen), > ; 7 Menufnflater is used to inflate the context mens from # menu esoutse. (You em also use add t0 add menu items.) ‘The callback method parameters ude the View that the user selected and a ConteaiMenv.ContextMenuinfo ‘object that provides additional information about the item selected. You mi use these parameters to determine ‘which context menu should be eresied, but in this example, all context menus forthe ae ity ae the came. ‘Then when the user selects an ites fen the contest menv, the system calls onContexthemSelected(), Have is an ‘example of how you can handle selected items: @overrive public boolean onConteatltemSelectes(Menultem ites) { A dapterContext Menulnfo info = (AdapterContextMenulafo) item getMemulnfo() sswiteh (tem getter) ¢ case R ideal editNote(infoig) case R a delete: #202, majeera Paza, Opp Adhye Trade Center, Ateerpet wowesaltechins.com Page 103Sai Technologies Ph: 9052124499/6699 UcieteNutefinoi), dlefault: Felurn super.onContextitemSelecteettem) “The strseture of this eos is similar wo the sam for Cresting ap Options Menu, in whieh lewd) queries the 1D fa the gelectal mene itson anda sith ststamnint maehes the nem 18 she HDe thet ave defined in the mene resource, And ike the options menu example. the detault statement cals the Soper class in eave it can ante mena ems wot handled hers, irecessaty 5 Iv this example, the selected tenn i an item fom 2 Lis ction on the selected fem the application weeds en knows the Hier ID f View}. Tr got tha 11, me ‘application cals geuMienulatol), which retwmns a AdapierView AdtapleeConiesiMenulaly clyeet that eludes the Dist 1D for she selected item inthe i fie, The lucal mets eiNuet) sad WelcteNaie() methods seeep this fist 1D to the eelected ham (i pritinn in the 1 ‘perfor an action onthe data spoeified by the ist ID. [Notes Items in a content menu do not support icons of chorteut keys: Creating Submenu |A.submenu ig 9 men thatthe user ean open by selecting, an item in snethsr mem Vows ean adds eubmnewu to any ‘menu fexcept a submesu). Submenvs are useful when your application has a Jot of fonctions that can Be organized {nwo vps, lke teins in & PC apptication's menu bar (File, Dat, View, et.) ‘When creating your meny ssyouree, you ean ercate @ aubmonu by adding e
, For example: asl versions"I.0" enceding="utt-8"7> ‘menu xmins-android="bp//schemas.androtd.comfapkires/andtotd’>
tay. By doing 60, other applivations will need to declare 2 corresponding ir own manifest to be able to start, stop, or bind to she service. Tn addition, a cervice can protect individual allo jimo it with permissions, by calling the method before exes :mplemestation of that call Provess Lifecyde The Android system sill auenpt (o heep dhe process hosting a service aruund ay lois ds dhe service has ‘een started gr has lieuts buund 1 i, Wher suusiag low on, memory aud needing to bill existing processes, ie priority ofa process hosting the service will be he bighe: uf the fullowiny possibilities + If te service is curently executing code in its ouCzeare(), onStartCommand0, or onDestrovd ‘methods, thei the hosting process will be a foreground process to ensure this code can execute without being kiled, ‘© Ifthe service ivas been started, then its hosting process is considered to be less important than any processes that are currently visible te the user on-screen, but mere important chan any process not visible, Because only a few processes are generally visible to the user, this means thet the service should not be killed except in extreme low memory conditions. ‘+ if there are clients dou 10 une service, then the service's Hosting process is never less important than the most important client. That is, if one of is clients is visible to the user, then the service itself is considered to be visible. ‘© A started service can’ ure the startForeground(int. Notification) API to put the service in a foregrmind state, where the system considers it to be something the user is actively aware of and thn not a candidate for killing when low on memory. (It is still thenretically possible for the service to be kalled under extreme memory pressure trom the current foreground application, but in practice this should not be a concern.) ———— 202 aera lta Op Ava Trae eter nee ‘westtehoncom Page 108Sai Technologies Ph: 9052124499/6699 Note this means that most of the time yonr service is mining, it may be killed hy the system if itis onder heavy memory pressure If this happens, the system will [ater try to restart the seevier An important consequence of ths 1s that af you implement opStanommand() to schedule work In be done asynchronously or in another thrend, then you may want fo use START FLAG REOELIVERY to have 2 the system re-deliver an Intent tor yow so that feloes not yet ost your sereiee 1s Kalle! wile process Other opplication componente running in the same process af the service (such as an Activity) can, of ‘courte, ineseace the importance of the overall process beyond just the importance of the service itself Local Service Sample ‘One of the most counnoa uses of a Service is.as a secondary component running alongside other parts of ‘au ayplivation, iu Wie sane process as the rest of the componenis. All compouenits uf au .aph rut iu the sainie pices unless explicitly stated otherwise, s6 this is 2 typical situation ‘When used in this way, by assuutting the components ate i dhe sane provess, you ean sacl sinupliy he interaction between, diem, clients of the service cau simply cast the [Binder they receive fiom it w a comcrete class published by the service, An example offtins ace of a Service is shown here, Fist is the Seivice itself, publishing a custom class when bound public class LocalService extends Service { private NotificationManager in!NM; /s nique identification Number for the Notification, (We use it on Notification start, and to cancel i private int NOTIFICATION = R.string.local_service_started: Public class LocalBinder extends Binder { LocalService getServiceQ) { rerum LocalService.this; 17202, Majera Fara, pp adiys Trade Center, Ameerpet ‘we stiechnoscom Page 109Sai lechnologies Ph: 9052124499/6699 @Overrde public void oxCreate() { NM = (NotificationManager)zetSystemServiec(NOTIFICATION SERVICE); 4 Display a nuuification about us starving. ‘We pus aa icon ia the status bar, shuwNuitivationt), GOvenide public int ouStartCormmsnd(tenn intent, int Days, int stared) Lowit"LocalServive", "Received start id" stastld +", "+ intent) i Wee want this sevice to continue tuning wutl it is eaplicity sf swopped, so return sticky. sca START STICKY, @Oveuide nds void ee Destroyd) 4 1 Cancel,the persistent notification. imNM cancel(NOTIFICATION): 1 Tell the user we stopped. “Toost.makeText(this, Rstring locel_secvies_stoppsd, Toast LENGTH_SHORT) show (}; ) @Override public [Binder onBind(Intent intent) { return mDinder; } 1) This isthe ubject that reveives interactions fiom clients. See 1 RemleService for a wiore wouslete cxsmple. private final Binder mBinder ~ uew LocalBinnder(), ———————— 20 sera az Op ave Tate ene, Ane vonsatechoscom| Page 110euUVY vw Sai Technologies Ph: 9052124499/6699 oy © Show a notifiention while this sevice is running ” private vord showNanfieatian() { /1 4p this sample, well nce she came text for the ticker snl the expanded nosifeston CharSequence test = get lexi{ Kt string leval_servies stare 1 Set the icon, setaling text and timestamp, Notihieation notification ew Novifiration(R drawable stat_sample, tex, ‘System enrrent iments) 1v"Uhe PenetingIntent ro launch our activity if the user selects this notification enatingtotent contentinrent = Pendinglatent getactvity(this, 0, new Intent(this, LocalServiceactivities.Controtter.class). 0), 1 Set che info for the views that show int the notification panel, notification.sexLatestEventlnfo(this, getPenu(R suing local service label}, text, comeutinten), 1 Send the wotifivation, aiNM.notify(NOTIFICATION, notification), Wii dat done, one can wow write client cude that directly avvesses the suuusiny service, suck as private LocalService mBoundService; private ServiceConnection Connection = new ServiceConnectionO { * ‘public void onServiceConnected(ComponentName className, [Binder service) { 1 This is called when the connection withthe service has been 1 established, giving us the service object we can use to i iteract with the service. Hecanse we have hound to a explicit 1 service that we know is ninning in ene own process, we can 1 east ite WRinder toa concrete class andl divectly access i #202; aera Per Opp diya Trade Cater, Areerpet stom Page 111Sal Technologies mBoundService ~ ((LacalService.LocalBin 11 Tel the user about this for our demo. ‘Toast makeText(Binding this, R string loca oust. LENGTH_SHORT)show() public void onServieeDisconnceted|Compone 4 This is called when the connection with Ph: 9052124499/6699 ogrvice).getService(); vice_eonnected, ane className) § sevice has been Wrunexpectedly disconnected ~ thet is, its p 9 erashed a 1 Because its running in eur some process should never 1 see this hoppen exBoundServiee ~ nulls ‘Toast mokeText(Binding.this, Rstringloea vice. dliseen! Yeast. LENGTH_ SHORT) show} void doBindServiee() { ‘1 Batabliha connection with the cervice, We an explicit Ji class name because we want a specific sery: suplemntation that / we know will be running in our own proces: cl thus won't be H! supporting component replacement by other ications) bindService(new Intent(Binding this, LocalService.class), mConnection, Conte HIND_AUTO_CREATE); mlsBound = true; 3 void doUnbindService() { if (mlsBound) ( é 1 Detach our existing conneetion. unbindService(mConneetion);, i rlsBound = false; 4 : : 19202 Meera Plaza, Opp Aditya Trade Center, Anes sees isco Page 112 oOyveuUe YY Q Sai Technologies Ph: 9052124499/6599 @Uvernde protected vord onDestray() { super.onLestroy() doUnbindServicel) Remote Messenger Service Sample If you need to be able to rite a Service that can pertorm complicated conumunication with cliente in ‘oatext startServiee to send commands to u), then you ean lessenger class instead of writing Holl AIDL files z remote processes (bayond simply the use vee the ‘An example of « Service that uses Messenger as ie client interface is shown here, First isthe Service itself, publiching a Messenger to an internal Handler when bound: public class MessengerServie extends Service { 9 For showing and hiding our notification. *! NofificationManager Nat} /* Keeps track of all euirent registered clients. */ AmayListeMecsenger> mClieite = new ArrayListeMesienger™O) #9 Hold lst value oot bya lien. */ fot mValue = pe * Command to the service to register 4 client, receiving callbacks * from the service. The Message’s replyTo field must be a Messenger of * the client where callbacks should oe sent ” static final int MSG_REGISTER_CLIENT = static final int MSG_UNREGISTER_CLIENT = 2; static final int MSG_SET_VALUE =3; lacs IncomingHandler extends Handler { Override SS ‘Ha02.Mayeera ana, Opp aaa rade Caner, Amero ‘wwassaeennscom Page 113Sai Technologies Ph: 9052124499/6699 public void handicNessage(Messave usu) { switch (imsg.whad { case MSG_REGISTER, CLIENT: mClients.add(ansg replyTo); break: case MSG_UNKEGISTER_CLIENT mC Tients remave(msg replyTor, veak: case MSG_SFT_VALUF Value = meg argh inlets nex().sene(Message.obtain(nuil, MSG_SET_VALUE, mValue, OD; } eaten (Remareeception €) { The client is dead, Remove it irom the lst ‘1 \e are going through the list from back to front 11 $0 this is safe 10 do inside the Joop. . Clients rernovetiy; break; etal: super-hanndleMessage(mse); y ) } pe * Target we publish for clients to send messages to IncomingHandler. ” Final Messenger mMessenger= new MessBager(new Incomingtandler); @owerriae 112, Majors Dans, Opp Arya Trade Contr, Ameer we crchnner sm Page 114 2 GO oO eoce coo aocooc ©Sai Technologies Ph: 9052124499/6699 public void onCreate() { mINM = (Notification Manay seSysteniService( NOTIFICATION. SERVICE), showNatificationd); @Override public void enDestroy0 { 1 Cancel the persistent notification. mNM.cancel(R string remote_service_stared) 1 Tell he user we stopped, Toast nukeText(this, Rolvingiemute service supped, Tus LENGTH SHORT) slut, * When binding to the service, we relum an interface to our messe! * for sending messages to the servies. Override public IBinder onBind(latent intent) [ return mMeasenger.getBinder(); * Show a notification while this service is running. " private void showNiotification() { 1m thie sample, well use the same text for the ticker and the expanded notification CharSequence text = gotText(Rstingremote_service_started); 1) Set the icon, scrolling text and timestamp ‘Notification notification ~ new Notficaion(R.drawable.stat sample, text 1208 Meers Placa, Opp Aahy Trade Center, Aneerpet smashes Page 115Sai Technologies Ph; 9052124499/6699 ‘System enrent limeMilisQ); i The Pendinglntent 19 launch our activity the user selects this natitication PendingIntent contentintent = Pendinglntent.gatActivity(this, 0, now Tatent(this. Contcatler-class), 0) WS the iufo for the views that chow in the notification panel. notification setLatesiEventInfo(thic, gerText(® stein text, contentlntent) 11 Send the notification, fi Weusea string rN Mnotify(R.str id because itis a unique number. We use it later 19 cancel remote serviee_started, notification): Hf we wont to make th vice run in a remote process (instead ofthe standard one for its apk), we ean ‘ace android:process in ite manifect tag to epecify one
‘Note that the waste “remute” choses here is arbitiay, aud you Gan use ulber names if you want additivual processes. The \' prefix appeals the e Ww your pachayre’s standard prouess ume. ‘With that cone, clients can now bind t0 the service and send messages to it. Note that this allows clients to register with it to receive messages back as well J" Messenger tor communicating wath service. */ Messenger mService = null J Flag indicating whether we have called bind on the service. *) Doolean misBound; J** Some text view we are using to show state information. */ TextView mCallbackText; i 11202, Msjccn aa Opp Aditya Tad Cater, Amserpt se coectnescem Page 116 o 8 ams ooe nooosocecsodsai Technologies a Ph: 9052124499/6699 * Handler of incoming messages from service. class IncomingHandler extends Handler { override public void handleMessage(Message mss) { svviteh (msgavhan) { case MessengerServieg MSG_SET_VALUE. mCallbackText.seiTextl"Received thom service break: + ausgael), defnult: swipe handle Message(mnse): * Tasyct we publish for clients to send messages to IncomingHandier final Messenger mMcssenger ~ new Measenger(new IncomingHandler()) oo * Clase for interocting with the main interface of the service, ” Private ServiceConnection mConnection = new ServieeConnection() { public void onServiceConnected(ComponentName className, Binder eervice) { 4 "This is called when the connection with the service has been 1 established, giving us the cervice object we ean use to JF interact with the cervice, We are commonicating with our 1! service through an IDL interface, so geta client-side 1! representation ofthat from the raw eervice object, mSeivice = new Messenger(serviee); ‘mCallbackTextsetTexi("Attached."); #202 Mojera aa Opp Adiga Trade Contes Ameerpet soaaechnosconn Page 117Sal Technologies Ph: 9057124499/6699 {1 We want 10 monitor he cervise fo: a long a8 we ars H connected it yf Message mag~ Mess M cobiain(oull, vice MSG_REGISTER_CLIENT): soplyTo~ Messer snBerviee sendfinsg) Service MEG_SEF VALUE. this husbCode(), 0) mse J enteh (RemoscException e) { 1 this ease the serviec has crashed before we could even 7 do aaythi 1g With it; 88 90 count on Yoon being disconnected (end then reconnected if it ° 1/30 there ia no need to do anything here. HAs part ofthe sample, tell the user what happened. ‘Toast nakeText(Binding thie, Rating remole_service_ connected, ‘Toast. LENGTH_SHORT).show(); - public void onServiceDisconnected(ComponentName clacsName) { 11 This ic called wen the connection with the cervice has been unexpectedly disconnected ~- that is, ite process erathed. Service = mul, mCallbackText.cetText("Diseonnected."); 11 Aa part of the sample, tell the user what happened. ‘Toost.mnakeText(Binding this, R.string remote_service_ disconnected, ‘Toast LENGTII_SIORT) show) ’ re aera Fla Op ha Tal Cr ep ‘rmwsaiearscom Page 118 3 Dp Oo ooo0o.e cowe 4 Sai Technologies Ph: 9052124499/6699 he void duBindSecvive) | Establish. a connection with dhe service, We use an explicit 1 class nasue because dere iy uy seasunt ty be uble ty Yer abr Hagplications replace our earuponet DdindServiee(new Inwen(Binwingdii, MessenuerSerice-vltos), mCumrection Contes BIND AUTO CREATE): uulsBound - bue, nCailbuchTextserPent "Binding; void dotinbindService() { if (alsBound) { I Ifswe bave received the service, and hence registered with 11, then now iste ine to wnregiter if (Service = null) { uy { ° Medsage nag ~ Message oboin(ll, MescengerService MSG 'UNREGISTER_CLIENT); snegraplyTo= mMessenges; Service cend(mneg); } catch (RemoteBxception e) { 11 There is nothing special we need to do if he service as crashed. 1 Detach our existing connection. unbindService(mConnection); mlsBound = false; mCallbackTextsetText("Unbinding."); J 11202, ojcera Pls, Op A rad Cntr Ameerpst swvmahechnocomn Page 119Sai Technologies Ph: 9052124499/669¢ Sim Con Bits returned by onSiartCommnand(Intent, int. int) eseriminy how to eontinne the serview Wits kiled int SPART_CONTINUATION } Unis 2 1s set qnStariCornmanUlotent, int, ant) the Intent sa re-delivery af 9 previeusly delivered inter int STARTFLAG REDELIVERY because the service had previously returned START REDELIVER INTEN but had been killed bolore calling stopSelffin) for 1 Intent This flag is set in onStartCommand{Javant ing, int) Fehe int START_FLAG RETRY Intent is aa retry because the original astempt never wot to or retumed from onStari(ommand( Intent, int, ind). Constant to return from onStanCommmand (pte tn): if this service's process i killed while it is started (citer retwrning from onStartConmand(inent int int}, int START NOL STICKY, and there are no new stat intents to deliver to it, then fake the service out of the started sate and don't rcreate wnt a unre expen eal to Context siaServicet intent Constant to return from onStariommand( Intent, int, ant): if this service's process 1s killed while it is started (otter retuming trom onStortommandntent, int int), then it wal be scheduled fora estar aud the ast iat START REDELIVER INTENT. ehivered Intent re-delivered to it again via onStartl intent int int) Constant to retum from onStarCommand(lntent, int int START STICKY. int): if this service's process is killed while tis started {ofier etuming from onStertCormmand (Intent. int. int), then leave it inthe started state but don't retin this, 1202, jean, Op Ain Tend Cote Anse srw sitecnascom Page oorooo$o oO oocooocooswi Sai Technologies Ph: 9052124499/6699 delivered intent Constant to return from onSianCommand( Intent, iat ind): com vertion of “ART_STICKY_COMPATIBIL yt ut “ ates that (#202, Majera Plaza, opp Ada Teade Cencer, ameerpet Page 121‘Sai Technologies Ph: 9052124499 /6699 Chapter 8: Broadcast Receivers ‘Many times the application needs to do come tasks in the back found for whieh user interventions io not required (05 very less intervention is required). These background processes keeps working even if user is same other application on the phone. Ty detine such backs: yond processes android has a concept af Services. Service in andvoid is uns lived + Interfese. Common example of sessice is Media Plaver evplication that heeps gayinrs sens Lacksiound, file dowuload avplication dat ea dust the file i te backgroue Lets see how to create 2 sevice. Creating a service Android has defined a base clas forall revices as “Service’, All he services have ro tend from this view clase, Service class defines service lifeeyele mai thous like onCreate(), onStart(), cnDestroy(). Here is the example a service élass package com. vissen.testApp.zervice; public class MyService extends Service { @Override a public IBinder onBind(intent inten) { return null ) @Override public void onCreate() { super.onCreate(); Toast. makeTexi(this, "Service ereated..", Toast LENGTH_LONG}.show(); @Override public void onDestroy() { super.onDestroy()s ‘Toast-makeText(this, "Bervice destroyed..", Toast LENGTIS LONG) show(); ene 1200. Mera Pa Op Aya Trade Cet. Ameer vsti Page 122 2ooO00 gO 06% ooocooce ooowe Sai Technologies Ph: 9052124199/6699 “The above service és notifying the user when the service is created and service is destioyeed. Like every thing else in and id, Service an andraid are also asseersted with the smvexts, Vis untent os required while using the service. he service entry has to be done in the AndroxdMkmulest.xiit file along swith the service inteot as shows below “service lass" service MyService"™ intent filter ~aotion andraid:value="eom.wicsen.testApp service MY_SERVICE" />
‘Now our service is ereated aned can be used by the application code Using the ine ‘The applicaiidn cau gait dhe service with the hely of CouertstasSesvive method. The uiediod will est) ue ouCreate ipetiod uf the sevice if service is uot alveady eeeted, ese onStant method will be called. Hicis the code to start the MyService Intent serviceIntent = new Intent() servicelntent sevAction(“com.wissen.testApp.ser vice MY_SERVICE"), SuariService(servicelntent), The service started with startService method will Keep on running until stopService() is called or ‘stopSelf() method is called, Another way to use service is to bind to the service. ‘The servi eee ata) ea ere requied by th syste oly fro ag 3 he calling cacti. bid othe sence 4 ene cooaesion objet ee o be ceted. The sesieecoseton chet lhe applizaon when he sie ts eonede do Botnet, Here how joa cn tind whe sevice ServieeConncetion conn ~ new ServiceConnection() { @Override 17200, Maeere en Opp Ay Tene Cente, Anesept veal coe Page 123Sai Technologies Ph: 9052124a99/66u9 public void onServiceConnceted(ComponentName name, [Binder service) { Logi("INFO", "Service bound"); @ Override public void onServiseDisconnected(ComponentName ary) { Lowi INFO", "Service Unbound". WirtlServicetimew Intent("couvissemsestAppsersice MY, SERVICE! Contes. BIND_AUTO_CREATE), ‘The applicaion can communicate with ihe service when application is connected with the service Generally the service communicate is done with tne help of Service Interface. Service interface defines ‘methods for which service can provider implementation, For example here is some interface pac ge com assem test puthiie intertace IySerwiee | puthite int perStamst nde) i Ussing this intetace the application ean ask the Service about is status. Lets see how the sevviee can support tis interlace, Previously we saw a method called onlbind which retum Linder object, the method {gals called whea some client of the service binds to the Service. ‘his 12 the same object that is passed to the onSeriieeConnevted method. The epplieaticn ean communicate with the service using this Inder ‘olyect. Heres how thie an be done: public class MyService extends Service { private it statusCode; private MyServiceBinder myServiceBinder ~ new MyServiceBinder() @Override public [Binder onBind(Intent intent) { return myServiecBinder; ! object of the clas that implements Service 3 public class MyServiceDinder extends Dinder implements MyService { public int getStatusCode() { _———— ee svg. sera rap Ain Trae Cone Ameer, onsetecmotom Page 124 gocoaoos coocoocosooeu ee uu ev Sai Technologies Ph: 9052124499/6699 return sransC ode: And here is how application can call gerStarusCode method: ServiceConncetion comn = new ServiceConnection() | @Ovenide. public void unServiveConmected(Componentanne name, Binder servive) { IMySeivive nySeivive = (IMyServive) service, statusCode ~ uivService xetStatusCode), Log.i("INEC", "Survive beau "), ‘You van alsu defiue ServiceListeues interface whieh ihe client of die service has 1a be implemented 10 ets update figm the service. Jn that case the service iuecface will have ty defice methods to revister and ‘nieyister the BerviceListener objects ‘Communication with Remote Service: The services that we defined unti! now run in the application processes, you can detine service that eau run ind ‘own process. For two processes to communicate with each other they nee! to marshal the ‘object to sent to other process. Axndeoid provide an ADL taol (Android Intertace definition Language) to handle all marshalling and commnineation part. ‘The service hao to provide the Service interface as an ail file, The AIDL tool will erate a java interface ‘conesponding for the aidl Service Interface. The AIDL tool also defines a stub class in the gencrated cervice interface, which implements the Service Interface (as abstract methods) and also provides some other required functionality. The service interface implementation clase has to extend this stub class and define the service interface methods. The service onBind method will return object of this implementation EE 1 Zag metraia, u tva trace enter, aneret vernstecoscom Page 125Sai Technologies Ph: 9052124499/6699 class so that the client application can use the service methods. Here is the how the communication can be done: ‘Create a file as IMyRemoteService.aidl as follows: pack ye com. wissen testAppy interface IMyRemoteServiee { ‘The eclipse android plug-in will create a Juv intesfaes for the aid file created above as the part of build process. The interface generated above will have a Siub inner class. Define a class that extends this study class, Here is the code for the RemoreService class package com.wissen.sestApP: ‘class RemoteService implements Service § int statusCode, @MOveuide public Binder ouBiud(uteut ax0) { a setuin inyRemoteServiceStub; : private IMyRemoteService.Stub myRemoteServiceSrub new IMyRemoteService.Siul() | public int getStatusCode() throws ReinoteException { return 0; ‘When the client application connect to the service the onServiceConnected method will be called and client will get the TBinder object of the service. The Stub class also provides a method to obtain the Service Interface object from the IBinder object. Here isthe client onServiceConnected code ServiceConneetion conn = new ServiceConnection() { @Override 202 Mera. Gop ia rate ene ane. venesnecnascom Page 126 oO oocse ecogonosd oO ftVw oe wee weer Sal Technologies Ph: 9052174499/6699 public void onServiceConnected(ComponentName name, [Binder eerviee) { IMyRemoteService myRemoteSorvice = IMyRemoteService Stulb solnterface(service); wy { statisCode = myRemoreSerview.geStatusCode(), | cateh (Remote septic handle exception Log.i("INFO", "Service bound"); Permissions: Service may specify required user permissions in che AndroidManifest.xml in
a Sintewetiber -<2ction androjdvalue="comwissen.testApp.service MY. SERVICE" >
-
You might also like
Sunbeam Corejava Notes
PDF
No ratings yet
Sunbeam Corejava Notes
80 pages
Struts2 Black Book
PDF
100% (3)
Struts2 Black Book
677 pages
PB Developing Android On Android Nov 2013
PDF
No ratings yet
PB Developing Android On Android Nov 2013
220 pages
Java
PDF
No ratings yet
Java
233 pages
Popegm
PDF
No ratings yet
Popegm
246 pages
New NTJ Spring PDF
PDF
100% (1)
New NTJ Spring PDF
282 pages
Spring-Hibernate-naresh Inst PDF
PDF
No ratings yet
Spring-Hibernate-naresh Inst PDF
472 pages
Introduction To DBMS Theory and Practicals
PDF
100% (1)
Introduction To DBMS Theory and Practicals
205 pages
Spring Complete Notes (Natraz)
PDF
No ratings yet
Spring Complete Notes (Natraz)
236 pages
PHP Naresh Technologies PDF
PDF
No ratings yet
PHP Naresh Technologies PDF
258 pages
Balu Sir New C PDF
PDF
No ratings yet
Balu Sir New C PDF
450 pages
CRT Aptitude Paid
PDF
No ratings yet
CRT Aptitude Paid
107 pages
NareshIT Oracle
PDF
100% (1)
NareshIT Oracle
140 pages
Servlets and JDBC
PDF
No ratings yet
Servlets and JDBC
12 pages
Git Workshop - PDF Version 1-Rotated
PDF
No ratings yet
Git Workshop - PDF Version 1-Rotated
36 pages
Web Dev Notes
PDF
No ratings yet
Web Dev Notes
270 pages
New Sateesh Yellanki (Oracle 10g)
PDF
No ratings yet
New Sateesh Yellanki (Oracle 10g)
398 pages
SDM Sunbeam Notes Vvimp
PDF
No ratings yet
SDM Sunbeam Notes Vvimp
316 pages
Ramchandra - Corejava (Update)
PDF
No ratings yet
Ramchandra - Corejava (Update)
603 pages
Asp Net
PDF
No ratings yet
Asp Net
274 pages
Android SM
PDF
No ratings yet
Android SM
77 pages
Nagoor Babu Pirnted Advance Java
PDF
No ratings yet
Nagoor Babu Pirnted Advance Java
352 pages
Java
PDF
No ratings yet
Java
160 pages
JDK Installation Guide
PDF
100% (1)
JDK Installation Guide
8 pages
Fullstack (Sashi Sir) PDF
PDF
No ratings yet
Fullstack (Sashi Sir) PDF
100 pages
Linux Lab Manual by Zoom PDF
PDF
No ratings yet
Linux Lab Manual by Zoom PDF
184 pages
Rapid Fire Sunbeam
PDF
No ratings yet
Rapid Fire Sunbeam
10 pages
Android Examples
PDF
No ratings yet
Android Examples
388 pages
Paper Presentation On Andriod
PDF
No ratings yet
Paper Presentation On Andriod
8 pages
Spring Cloud
PDF
No ratings yet
Spring Cloud
661 pages
Corejava - 24 11 2015
PDF
No ratings yet
Corejava - 24 11 2015
390 pages
Oracle Madhu Sir
PDF
No ratings yet
Oracle Madhu Sir
352 pages
Volume 2 Final
PDF
No ratings yet
Volume 2 Final
199 pages
Nagoor Babu Core Java
PDF
No ratings yet
Nagoor Babu Core Java
678 pages
JDBC Ratan
PDF
No ratings yet
JDBC Ratan
71 pages
Raghu Java Programming
PDF
No ratings yet
Raghu Java Programming
120 pages
Android Sai Tech PDF
PDF
No ratings yet
Android Sai Tech PDF
166 pages
Hibernate 2
PDF
No ratings yet
Hibernate 2
115 pages
Android Application Development
PDF
No ratings yet
Android Application Development
156 pages
DBT Notes PDF
PDF
No ratings yet
DBT Notes PDF
79 pages
Java Package PDF
PDF
No ratings yet
Java Package PDF
2 pages
Cognizant Internship Report
PDF
No ratings yet
Cognizant Internship Report
54 pages
SQL by Jai Shankar Sir
PDF
No ratings yet
SQL by Jai Shankar Sir
158 pages
Presented By:: Guided By::: Zaveri Nainesh - Ms Vidhi Mankadiya
PDF
No ratings yet
Presented By:: Guided By::: Zaveri Nainesh - Ms Vidhi Mankadiya
43 pages
PL - SQL Useful Examples
PDF
No ratings yet
PL - SQL Useful Examples
37 pages
RESTFul Services
PDF
No ratings yet
RESTFul Services
25 pages
DAC Class Room Notes
PDF
No ratings yet
DAC Class Room Notes
44 pages
PENTAGON SPACE - Java Full Stack Brochure New Syllabus 01
PDF
No ratings yet
PENTAGON SPACE - Java Full Stack Brochure New Syllabus 01
10 pages
Android Final 2
PDF
No ratings yet
Android Final 2
65 pages
Vector Booklet Full Stack Final - v7 - Without - Bleed-Compressed
PDF
No ratings yet
Vector Booklet Full Stack Final - v7 - Without - Bleed-Compressed
18 pages
An DR Oid: CH No Lo Gy
PDF
No ratings yet
An DR Oid: CH No Lo Gy
25 pages
Linux Intro
PDF
No ratings yet
Linux Intro
40 pages
Programming: Unit #2: Object-Oriented Programmin
PDF
No ratings yet
Programming: Unit #2: Object-Oriented Programmin
1 page
Android Zensar
PDF
No ratings yet
Android Zensar
45 pages
Android Unit1
PDF
No ratings yet
Android Unit1
54 pages
SQL PL SQL Content
PDF
No ratings yet
SQL PL SQL Content
4 pages
Mad Unit 1
PDF
No ratings yet
Mad Unit 1
11 pages
Data Science Content
PDF
No ratings yet
Data Science Content
4 pages
Android Mos
PDF
No ratings yet
Android Mos
14 pages
Android
PDF
No ratings yet
Android
12 pages