android service pattern

Upload: lorenzo-bartoli

Post on 04-Jun-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Android Service Pattern

    1/40

    CHAPTER 1-

    ;vance "ervice Patterns

    n The Busy Coder's Guide to Android Deveopment, e 'o!ere" ho to

    'reate an" 'onsume ser!i'es an" 'o!ere" some basi' ser!i'e patterns.+oe!er, ser!i'es 'an 'ertainly "o more than hat is 'o!ere" in thoseintro"u'tory patterns. n this 'hapter, e ill e>amine some more poer&uloptions &or ser!i'es, in'lu"ing remote ser!i'es an" using ser!i'es in the roleo& G'ron NobsG or Gs'he"ule" tasksG.

    Cemote "ervices

    y "e&ault, ser!i'es are use" ithin the appli'ation that publishes them.+oe!er, it is possible to e>pose ser!i'es &or other appli'ations to takea"!antage o&. 8hese are basi'ally inter-pro'ess e"itions o& the bin"ingpattern an" 'omman" patterns outline" in The Busy Coder's Guide toAndroid Deveopment.

    We start ith an e>planation o& the inter-pro'ess 'ommuni'ation (#C)me'hanism o&&ere" in An"roi" &or alloing ser!i'es to ork ith 'lients inother appli'ations. 8hen, e mo!e onto the steps to allo a 'lient to

    'onne't to a remote ser!i'e, be&ore "es'ribing ho to turn an or"inaryser!i'e into a remote one. We then look at ho one 'an implement a'allba'k system to allo ser!i'es, through #C, to pass in&ormation ba'k to'lients. A&ter noting the possibility o& bin"er errors, e rap by e>aminingother ays to get results &rom remote ser!i'es, ba'k to 'lients, ithoutgoing through bin"ing.

    '30

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    2/40

    ;vance "ervice Patterns

    'hen $PC Attac?s

    %er!i'es ill ten" to o&&er #C as a means o& intera'ting ith a'ti!ities orother An"roi" 'omponents. @a'h ser!i'e "e'lares hat metho"s it is

    making a!ailable o!er #CP those metho"s are then a!ailable &or other'omponents to 'all, ith An"roi" han"ling all the messy "etails in!ol!e"

    ith making metho" 'alls a'ross 'omponent or pro'ess boun"aries.

    8he guts o& this, &rom the stan"point o& the "e!eloper, is e>presse" in ADLthe An"roi" nter&a'e Des'ription Language. & you ha!e use" #Cme'hanisms like CFM, CFA, or the like, you ill re'ognie the notion o&DL. ADL "es'ribes the publi' #C inter&a'e, an" An"roi" supplies tools tobuil" the 'lient an" ser!er si"e o& that inter&a'e.

    With that in min", let:s take a look at ADL an" #C.

    Write the AI$/

    DLs are &re?uently ritten in a Glanguage-neutralG synta>. ADL, on theother han", looks a lot like a a!a inter&a'e. *or e>ample, here is some

    ADL

    packagecom.commonsware.android.advservice5

    "" >eclare t0e interface.interfaceIScript; voide(ecuteScriptStringscript!5A

    As ith a a!a inter&a'e, you "e'lare a pa'kage at the top. As ith a a!ainter&a'e, the metho"s are rappe" in an inter&a'e "e'laration (interfaceIScript ; ... A). An", as ith a a!a inter&a'e, you list the metho"s you are

    making a!ailable.

    8he "i&&eren'es, though, are 'riti'al.

    *irst, not e!ery a!a type 'an be use" as a parameter. Bour 'hoi'es are

    '3&

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    3/40

    ;vance "ervice Patterns

    #rimiti!e !alues (int, float, double, boolean, et'.)

    Stringan" C0arSeBuence

    istan" 8ap(&rom java.util)

    Any other ADL-"e&ine" inter&a'es

    Any a!a 'lasses that implement the tension an" pla'e them in theproper "ire'tory base" on the pa'kage name.

    When you buil" your proNe't, either !ia an D@ or !ia Ant, the aidlutility&rom the An"roi" %DK ill translate your ADL into a ser!er stub an" a'lient pro>y.

    Ipleent the Interface

    ;i!en the ADL-'reate" ser!er stub, no you nee" to implement theser!i'e, either "ire'tly in the stub, or by routing the stub implementation toother metho"s you ha!e alrea"y ritten.

    '31

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    4/40

    ;vance "ervice Patterns

    8he me'hani's o& this are &airly straight&orar"

    Create a pri!ate instan'e o& the ADL-generate" .Stub 'lass (e.g.,IScript.Stub)

    mplement metho"s mat'hing up ith ea'h o& the metho"s youpla'e" in the ADL

    eturn this pri!ate instan'e &rom your on7ind! metho" in theServicesub'lass

    ote that ADL #C 'alls are syn'hronous, an" so the 'aller is blo'ke" untilthe #C metho" returns. +en'e, your ser!i'es nee" to be ?ui'k about their

    ork.

    We ill see e>amples o& ser!i'e stubs later in this 'hapter.

    A Consumer Economy

    F& 'ourse, e nee" to ha!e a 'lient &or ADL-"e&ine" ser!i'es, lest theseser!i'es &eel lonely.

    )ound for Success

    8o use an ADL-"e&ine" ser!i'e, you &irst nee" to 'reate an instan'e o& youron ServiceConnection 'lass. ServiceConnection, as the name suggests,represents your 'onne'tion to the ser!i'e &or the purposes o& making #C'alls.

    Bour ServiceConnectionsub'lass nee"s to implement to metho"s

    1. onServiceConnected!, hi'h is 'alle" on'e your a'ti!ity is boun" to

    the ser!i'e

    2. onService>isconnected!, hi'h is 'alle" i& your 'onne'tion en"snormally, su'h as you unbin"ing your a'ti!ity &rom the ser!i'e

    '33

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    5/40

    ;vance "ervice Patterns

    @a'h o& those metho"s re'ei!es a Component9ame, hi'h simply i"enti&ies theser!i'e you 'onne'te" to. More importantly, onServiceConnected!re'ei!esan I7inderinstan'e, hi'h is your gateay to the #C inter&a'e. Bou ill

    ant to 'on!ert the I7inderinto an instan'e o& your ADL inter&a'e 'lass, so

    you 'an use #C as i& you ere 'alling regular metho"s on a regular a!a'lass (IScript.Stub.asInterfacebinder!).

    8o a'tually hook your a'ti!ity to the ser!i'e, 'all bindService! on thea'ti!ity

    bindServicenewIntent)com.commonsware.android.advservice.IScript) !@ svcConn@Conte%t.7I9>16E?41C=:6?:!5

    8hebindService!

    metho" takes three parameters1. An Intentrepresenting the ser!i'e you ish to in!oke

    2. Bour ServiceConnectioninstan'e

    /. A set o& &lags O most times, you ill ant to pass in7I9>16E?41C=:6?:, hi'h ill start up the ser!i'e i& it is not alrea"yrunning

    A&ter your bindService! 'all, your onServiceConnected! 'allba'k in the

    ServiceConnection ill e!entually be in!oke", at hi'h time your'onne'tion is rea"y &or use.

    Re0uest for Service

    Fn'e your ser!i'e inter&a'e obNe't is rea"y(IScript.Stub.asInterfacebinder!), you 'an start 'alling metho"s on it as

    you nee" to. n &a't, i& you "isable" some i"gets aaiting the 'onne'tion,no is a &ine time to re-enable them.

    +oe!er, you ill ant to trap to e>'eptions. Fne is >ead4bject:%ceptionO i& this is raise", your ser!i'e 'onne'tion terminate" une>pe'te"ly. n this'ase, you shoul" unin" your use o& the ser!i'e, perhaps by 'allingonService>isconnected! manually, as shon abo!e. 8he other is=emote:%ception, hi'h is a more general-purpose e>'eption in"i'ating a

    '35

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    6/40

    ;vance "ervice Patterns

    'ross-pro'ess 'ommuni'ations problem. Again, you shoul" probably 'easeyour use o& the ser!i'e.

    #etting Unbound

    When you are "one ith the #C inter&a'e, 'all unbindService!, passing inthe ServiceConnection. @!entually, your 'onne'tion:sonService>isconnected!'allba'k ill be in!oke", at hi'h point you shoul"null out your inter&a'e obNe't, "isable rele!ant i"gets, or otherise &lag

    yoursel& as no longer being able to use the ser!i'e.

    Bou 'an alays re'onne't to the ser!i'e, !ia bindService!, i& you nee" to

    use it again.

    "ervice 5rom A*ar

    @!erything &rom the pre'e"ing to se'tions 'oul" be use" by lo'al ser!i'es.n &a't, that prose originally appeare" in The Busy Coder's Guide to AndroidDeveopment spe'i&i'ally in the 'onte>t o& lo'al ser!i'es. +oe!er, ADLa""s a &air bit o& o!erhea", hi'h is not ne'essary ith lo'al ser!i'es. A&terall, ADL is "esigne" to marshal its parameters an" transport them a'ross

    pro'ess boun"aries, hi'h is hy there are so many ?uirky rules abouthat you 'an an" 'annot pass as parameters to your ADL-"e&ine" A#s.

    %o, gi!en our ADL "es'ription, let us e>amine some implementations,spe'i&i'ally &or remote ser!i'es.

    Fur sample appli'ations O shon in the 6dvServices"=emoteService an"6dvServices"=emoteClient sample proNe'ts O 'on!ert our eanshell "emo&rom The Busy Coder's Guide to Android Deveopmentinto a remote ser!i'e.

    & you a'tually ante" to use s'ripting in an An"roi" appli'ation, iths'ripts loa"e" o&& o& the nternet, isolating their e>e'ution into a ser!i'emight not be a ba" i"ea. n the ser!i'e, those s'ripts are san"bo>e", onlyable to a''ess &iles an" A#s a!ailable to that ser!i'e. 8he s'ripts 'annota''ess your on appli'ation:s "atabases, &or e>ample. & the s'ript-e>e'uting

    '36

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    7/40

    ;vance "ervice Patterns

    ser!i'e is kept tightly 'ontrolle", it minimies the mis'hie& a rogue s'ript'oul" possibly "o.

    Service 1aes

    8o bin" to a ser!i'e:s ADL-"e&ine" A#, you nee" to 'ra&t an ntent that 'ani"enti&y the ser!i'e in ?uestion. n the 'ase o& a lo'al ser!i'e, that ntent 'anuse the lo'al approa'h o& "ire'tly re&eren'ing the ser!i'e 'lass.

    Fb!iously, that is not possible in a remote ser!i'e 'ase, here the ser!i'e'lass is not in the same pro'ess, an" may not e!en be knon by name tothe 'lient.

    When you "e&ine a ser!i'e to be use" by remote, you nee" to a"" an intent-&ilter element to your ser!i'e "e'laration in the mani&est, in"i'ating ho

    you ant that ser!i'e to be re&erre" to by 'lients. 8he mani&est &or=emoteServiceis shon belo

    &'%mlversion()$.)encoding()utf-+)',&manifestandroid/versionCode()$) android/version9ame()$.) package()com.commonsware.android.advservice) %mlns/android()0ttp/""sc0emas.android.com"apk"res"android) ,

    &uses-sdkandroid/minSdkVersion()O)

    android/targetSdkVersion()N)", &supports-screensandroid/largeScreens()false) android/normalScreens()true) android/smallScreens()false)", &applicationandroid/icon()2drawable"cw) android/label()2string"app1name), &serviceandroid/name().7s0Service), &intent-filter, &actionandroid/name()com.commonsware.android.advservice.IScript) ", &"intent-filter, &"service, &"application,&"manifest,

    +ere, e say that the ser!i'e 'an be i"enti&ie" by the namecom.commonsware.android.advservice.IScript . %o long as the 'lient uses thisname to i"enti&y the ser!i'e, it 'an bin" to that ser!i'e:s A#.

    '37

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    8/40

    ;vance "ervice Patterns

    n this 'ase, the name is not an implementation, but the ADL A#, as youill see belo. n e&&e't, this means that so long as some ser!i'e e>ists onthe "e!i'e that implements this A#, the 'lient ill be able to bin" tosomething.

    The Service

    eyon" the mani&est, the ser!i'e implementation is not too unusual. 8hereis the ADL inter&a'e, IScript

    packagecom.commonsware.android.advservice5

    "" >eclare t0e interface.interfaceIScript;

    voide(ecuteScriptStringscript!5A

    An" there is the a'tual ser!i'e 'lass itsel&, 7s0Service

    packagecom.commonsware.android.advservice5

    importandroid.app.Service5importandroid.content.Intent5importandroid.os.I7inder5importandroid.util.og5importbs0.Interpreter5

    publicclass7s0Servicee%tendsService ; privatefinalIScript.Stubbinder(newIScript.Stub!; publicvoide(ecuteScriptStringscript!; e(ecuteScriptImplscript!5 A A5 privateInterpreteri(newInterpreter!5

    24verride publicvoidonCreate!; super.onCreate!5

    tr; i.set)conte%t)@t0is!5 A catc0bs0.:val:rrore!; og.e)7s0Service)@):rror e%ecuting script)@e!5 A A

    '58

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    9/40

    ;vance "ervice Patterns

    24verride publicI7inderonBindIntentintent!; returnbinder!5 A

    24verride

    publicvoidon"estroy!; super.on"estroy!5 A

    privatevoide(ecuteScriptImplStringscript!; tr; i.evalscript!5 A catc0bs0.:val:rrore!; og.e)7s0Service)@):rror e%ecuting script)@e!5 A AA

    & you ha!e seen the ser!i'e an" eanshell samples in The Busy Coder'sGuide to Android Deveopmentthen this implementation ill seem &amiliar.8he biggest thing to note is that the ser!i'e returns no result an" han"lesany errors lo'ally. +en'e, the 'lient ill not get any response ba'k &rom thes'ript O the s'ript ill Nust run. n a real implementation, this oul" be silly,an" e ill ork to re'ti&y this later in this 'hapter.

    Also note that, in this implementation, the s'ript is e>e'ute" "ire'tly by the

    ser!i'e on the 'alling threa". Fne might think this is not a problem, sin'ethe ser!i'e is in its on pro'ess an", there&ore, 'annot possibly be using the'lient:s $ threa". +oe!er, ADL #C 'alls are syn'hronous, so the 'lient

    ill still blo'k aiting &or the s'ript to be e>e'ute". 8his too ill be'orre'te" later in this 'hapter.

    The Client

    8he 'lient O 7s0Service>emo out o& 6dvServices"=emoteClient O is a &airlystraight-&orar" mashup o& the ser!i'e an" eanshell 'lients, ith totists

    packagecom.commonsware.android.advservice.client5

    importandroid.app.6ctivit5

    '5/

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    10/40

    ;vance "ervice Patterns

    importandroid.app.6lert>ialog5importandroid.content.Component9ame5importandroid.content.Conte%t5importandroid.content.Intent5importandroid.content.ServiceConnection5importandroid.os.7undle5

    importandroid.os.I7inder5importandroid.view.View5importandroid.widget.7utton5importandroid.widget.:dit?e%t5importcom.commonsware.android.advservice.IScript5

    publicclass7s0Service>emoe%tends6ctivit ; privateIScriptservice(null5 privateServiceConnectionsvcConn(newServiceConnection!; publicvoidonServiceConnectedComponent9ameclass9ame@ I7inderbinder!; service(IScript.Stub.asInterfacebinder!5 A

    publicvoidonService"isconnectedComponent9ameclass9ame!; service(null5 A A5

    24verride publicvoidonCreate7undleicicle!; super.onCreateicicle!5 setContentView=.laout.main!5

    7uttonbtn(7utton!findViewById=.id.eval!5 final:dit?e%tscript(:dit?e%t!findViewById=.id.script!5

    btn.set$nClic)ListenernewView.$nClic)Listener!; publicvoidonClic)Viewview!; Stringsrc(script.get+e(t!.toString!5

    tr; service.e(ecuteScriptsrc!5 A catc0android.os.=emote:%ceptione!; 6lert>ialog.7uilderbuilder( new6lert>ialog.Builder7s0Service>emo.t0is!5

    builder .set+itle):%ceptionM)!

    .set'essagee.toString!! .setositiveButton)4U)@null! .s!ow!5 A A A!5

    bindServicenewIntent)com.commonsware.android.advservice.IScript) !@

    '5'

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    11/40

    ;vance "ervice Patterns

    svcConn@Conte%t.7I9>16E?41C=:6?:!5 A

    24verride publicvoidon"estroy!; super.on"estroy!5

    unbindServicesvcConn!5

    AA

    Fne tist is that the 'lient nee"s its on 'opy o& IScript.aidl. A&ter all, it isa totally separate appli'ation, an" there&ore "oes not share sour'e 'o"e

    ith the ser!i'e. n a pro"u'tion en!ironment, e might 'ra&t an""istribute a A &ile that 'ontains the IScript'lasses, so both 'lient an"ser!i'e 'an ork o&& the same "e&inition (see the up'oming 'hapter on

    reusable 'omponents). *or no, e ill Nust ha!e a 'opy o& the ADL.

    8hen, the bindService! 'all uses a slightly "i&&erent Intent, one thatre&eren'es the name the ser!i'e is registere" un"er, an" that is the glue thatallos the 'lient to &in" the mat'hing ser!i'e.

    & you 'ompile both appli'ations an" uploa" them to the "e!i'e, then startup the 'lient, you 'an enter in eanshell 'o"e an" ha!e it be e>e'ute" bythe ser!i'e. ote, though, that you 'annot per&orm $ operations (e.g., raise

    a ?oast) &rom the ser!i'e. & you 'hoose some s'ript that is long-running,you ill see that the ;o= button is blo'ke" until the s'ript is 'omplete

    '50

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    12/40

    ;vance "ervice Patterns

    #igure 382 The Bsh"ervice=emo application, running a long script

    "ervicin# the "ervice

    8he pre'e"ing se'tion outline" to &las in the implementation o& theeanshell remote ser!i'e

    1. 8he 'lient re'ei!e" no results &rom the s'ript e>e'ution

    2. 8he 'lient blo'ke" aiting &or the s'ript to 'omplete

    & e ere not orrie" about the blo'king-'all issue, e 'oul" simply ha!ethe e%ecuteScript!e>porte" A# return some sort o& result (e.g., toString!on the result o& the eanshell eval!'all). +oe!er, that oul" not sol!ethe &a't that 'alls to ser!i'e A#s are syn'hronous e!en &or remote ser!i'es.

    Another approa'h oul" be to pass some sort o& 'allba'k obNe't ithe%ecuteScript!, su'h that the ser!er 'oul" run the s'ript asyn'hronouslyan" in!oke the 'allba'k on su''ess or &ailure. 8his, though, implies thatthere is some ay to ha!e the a'ti!ity e>port an A# to the ser!i'e.

    '5&

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    13/40

    ;vance "ervice Patterns

    *ortunately, this is eminently "oable, as you ill see in this se'tion, an" thea''ompanying samples (6dvServices"=emoteService:% an"6dvServices"=emoteClient:%).

    Callbac*s via AI$/

    ADL "oes not ha!e any 'on'ept o& "ire'tion. t Nust knos inter&a'es an"stub implementations. n the pre'e"ing e>ample, e use" ADL to ha!e theser!i'e &lesh out the stub implementation an" ha!e the 'lient a''ess theser!i'e !ia the ADL-"e&ine" inter&a'e. +oe!er, there is nothing magi'about ser!i'es implementing an" 'lients a''essing O it is e?ually possible tore!erse matters an" ha!e the 'lient implement something the ser!i'e uses

    !ia an inter&a'e.

    %o, &or e>ample, e 'oul" 'reate an IScript=esult.aidl&ile

    packagecom.commonsware.android.advservice5

    "" >eclare t0e interface.interfaceIScript=esult; voidsuccessStringresult!5 voidfailureStringerror!5A

    8hen, e 'an augment IScript itsel&, to pass an IScript=esult ithe%ecuteScript!

    packagecom.commonsware.android.advservice5

    importcom.commonsware.android.advservice.IScript=esult5

    "" >eclare t0e interface.interfaceIScript; voide(ecuteScriptStringscript@IScript=esultcb!5A

    oti'e that e nee" to spe'i&i'ally import IScript=esult, Nust like e mightimport some GregularG a!a inter&a'e. An", as be&ore, e nee" to make surethe 'lient an" the ser!er are orking o&& o& the same ADL "e&initions, sothese to ADL &iles nee" to be repli'ate" a'ross ea'h proNe't.

    '51

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    14/40

    ;vance "ervice Patterns

    ut other than that one little tist, this is all that is re?uire", at the ADLle!el, to ha!e the 'lient pass a 'allba'k obNe't to the ser!i'e "e&ine the

    ADL &or the 'allba'k an" a"" it as a parameter to some ser!i'e A# 'all.

    F& 'ourse, there is a little more ork to "o on the 'lient an" ser!er si"e tomake use o& this 'allba'k obNe't.

    Revising the Client

    Fn the 'lient, e nee" to implement an IScript=esult. Fn success!, e'an "o something like raise a ?oastP on failure!, e 'an perhaps sho an6lert>ialog.

    8he 'at'h is that e 'annot be 'ertain e are being 'alle" on the $ threa"in our 'allba'k obNe't.

    %o, the sa&est ay to "o that is to make the 'allba'k obNe't use somethinglike run4nEi?0read!to ensure the results are "isplaye" on the $ threa"

    privatefinalIScript=esult.Stubcallback(newIScript=esult.Stub!; publicvoidsuccessfinalStringresult!; run$nUi+!readnewRunnable!;

    publicvoidrun!; successImplresult!5 A A!5 A

    publicvoidfailurefinalStringerror!; run$nUi+!readnewRunnable!; publicvoidrun!; failureImplerror!5 A A!5 AA5

    privatevoidsuccessImplStringresult!; ?oast .ma)e+e(t7s0Service>emo.t0is@result@?oast.:9#?149#! .s!ow!5A

    privatevoidfailureImplStringerror!;

    '53

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    15/40

    ;vance "ervice Patterns

    6lert>ialog.7uilderbuilder( new6lert>ialog.Builder7s0Service>emo.t0is!5

    builder .set+itle):%ceptionM)! .set'essageerror!

    .setositiveButton)4U)@null! .s!ow!5A

    An", o& 'ourse, e nee" to up"ate our 'all to e%ecuteScript!to pass the'allba'k obNe't to the remote ser!i'e

    24verridepublicvoidonCreate7undleicicle!; super.onCreateicicle!5 setContentView=.laout.main!5

    7uttonbtn(7utton!findViewById=.id.eval!5 final:dit?e%tscript(:dit?e%t!findViewById=.id.script!5

    btn.set$nClic)ListenernewView.$nClic)Listener!; publicvoidonClic)Viewview!; Stringsrc(script.get+e(t!.toString!5

    tr; service.e(ecuteScriptsrc@callback!5 A catc0android.os.=emote:%ceptione!; failureImple.toString!!5 A A A!5bindServicenewIntent)com.commonsware.android.advservice.IScript) !@

    svcConn@Conte%t.7I9>16E?41C=:6?:!5A

    Revising the Service

    8he ser!i'e also nee"s 'hanging, to both e>e'ute the s'ripts asyn'hronously

    an" use the supplie" 'allba'k obNe't &or the en" results o& the s'ript:se>e'ution.

    7s0Service &rom 6dvServices"=emoteService:% uses the inked7locking[ueuepattern to manage a ba'kgroun" threa". An :%ecuteScriptJobraps up thes'ript an" 'allba'kP hen the Nob is e!entually pro'esse", it uses the

    '55

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    16/40

    ;vance "ervice Patterns

    'allba'k to supply the results o& the eval!(on su''ess) or the message o&the :%ception(on &ailure)

    packagecom.commonsware.android.advservice5

    importandroid.app.Service5importandroid.content.Intent5importandroid.os.I7inder5importandroid.util.og5importjava.util.concurrent.inked7locking[ueue5importbs0.Interpreter5

    publicclass7s0Servicee%tendsService ; privatefinalIScript.Stubbinder(newIScript.Stub!; publicvoide(ecuteScriptStringscript@IScript=esultcb!; e(ecuteScriptImplscript@cb!5 A A5

    privateInterpreteri(newInterpreter!5 privateinked7locking[ueue&Job,B(newinked7locking[ueue&Job,!5

    24verride publicvoidonCreate!; super.onCreate!5

    new+!readB

  • 8/13/2019 Android Service Pattern

    17/40

    ;vance "ervice Patterns

    publicvoidrun!; w0iletrue!; tr; Jobj(B.ta)e!5

    ifj.stop+!read!!;

    break5 A else; j.process!5 A A catc0Interrupted:%ceptione!; break5 A A A A5

    classJob; booleanstop+!read!; returnfalse!5 A

    voidprocess!; "" no-op A A

    classUillJobe%tendsJob ; 24verride booleanstop+!read!; returntrue!5

    A A

    class:%ecuteScriptJobe%tendsJob ; IScript=esultcb5 Stringscript5

    E(ecuteScriptJobStringscript@IScript=esultcb!; t0is.script(script5 t0is.cb(cb5 A

    voidprocess!;

    tr; cb.successi.evalscript!.toString!!5 A catc0?0rowablee!; og.e)7s0Service)@):rror e%ecuting script)@e!5

    tr; cb.failuree.get'essage!!5

    '57

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    18/40

    ;vance "ervice Patterns

    A catc0?0rowablet!; og.e)7s0Service)@ ):rror returning e%ception to client)@ t!5 A

    A A AA

    oti'e that the ser!i'e:s on A# Nust nee"s the IScript=esultparameter,hi'h 'an be passe" aroun" an" use" like any other a!a obNe't. 8he &a'tthat it happens to 'ause 'alls to be ma"e syn'hronously ba'k to the remote'lient is in!isible to the ser!i'e.

    8he net result is that the 'lient 'an 'all the ser!i'e an" get its resultsithout tying up the 'lient:s $ threa".

    Bou may be on"ering hy e "o not simply use an 6snc?ask. 8he reasonis that remote ser!i'e metho"s e>pose" by ADL are not in!oke" on themain appli'ation threa" O one o& the &e pla'es in An"roi" here An"roi"'alls your 'o"e &rom a ba'kgroun" threa". An 6snc?ask e>pe'ts to be'reate" on the main appli'ation threa".

    The Bind That 5ails

    %ometimes, a 'all to bindService!ill &ail &or some reason. 8he most'ommon 'ause ill be an in!ali" IntentO &or e>ample, you might be tryingto bin" to a Service that you &aile" to register in the mani&est. 8hebindService! metho" returns a boolean!alue in"i'ating hether or notthere as an imme"iate problem, so you 'an take appropriate steps.

    *or lo'al ser!i'es, this is usually Nust a 'o"ing problem. *or remote ser!i'es,though, it 'oul" be that the ser!i'e you are trying to ork ith has notbeen installe" on the "e!i'e. Bou ha!e to approa'hes &or "ealing ith this

    1. Bou 'an at'h &or bindService! to return falsean" assume thatmeans the ser!i'e is not installe"

    '68

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    19/40

    ;vance "ervice Patterns

    2. Bou 'an use introspe'tion to see i& the ser!i'e is in"ee" installe"be&ore you e!en try 'alling bindService!

    We ill look at introspe'tion te'hni?ues later in this book.

    $* the Bindin# $s Too Ti#ht

    %ometimes, bin"ing is more than you really nee".

    %en"ing "ata to a remote ser!i'e is easy, e!en ithout bin"ing. ust pa'kagesome "ata in Intente>tras an" use that Intentin a startService!'all. 8heremote ser!i'e 'an grab those e>tras an" operate on that "ata. 8his orks

    best ith an IntentService, hi'h "oes three things to assist ith thispattern

    1. t passes the Intents, ith their e>tras, to your 'o"e inonandleIntent!on a ba'kgroun" threa", so you 'an take as long as

    you ant to pro'ess them

    2. t ?ueues up Intents, so i& another one arri!es hile you are orkingon a pre!ious one, there is no problem

    /. t automati'ally shuts "on the ser!i'e hen there is no more ork

    to be "one

    8he biggest issue is getting results ba'k to the 'lient. 8here is no possibilityo& a 'allba'k i& there is no bin"ing.

    *ortunately, An"roi" o&&ers some alternati!es that ork ni'ely ith thisapproa'h.

    Private )roadcasts

    8he 'on'ept o& a Gpri!ate broa"'astG may seem like an o>ymoron, but it issomething a!ailable to you in An"roi".

    '6/

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    20/40

    ;vance "ervice Patterns

    %en"ing a broa"'ast Intent is &airly easy O 'reate the Intent an" 'allsend7roadcast!. +oe!er, by "e&ault, any appli'ation 'oul" &iel" a7roadcast=eceiver to at'h &or your broa"'ast. 8his may or may not'on'ern you.

    & you &eel that GspiesG 'oul" be troublesome, you 'an 'all setample.

    )shService2 Revisited

    Let us take a 'loser look at those to te'hni?ues, as implemente" in6dvServices"=emoteClientEnbound an" 6dvServices"=emoteServiceEnbound .8hese !ersions o& the eanshell sample are "esigne" to "emonstrate bothpri!ate broa"'asts an" pen"ing results.

    '6'

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    21/40

    ;vance "ervice Patterns

    ;larm:anager@ :aking the "ervices Cun .nTime

    A 'ommon ?uestion hen "oing An"roi" "e!elopment is Ghere "o setup cronNobsJG

    8he cronutility O popular in Linu> O is a ay o& s'he"uling ork to be "oneperio"i'ally. Bou tea'h cronhat to run an" hen to run it (e.g., eek"aysat noon), an" crontakes 'are o& the rest. %in'e An"roi" has a Linu> kernelat its heart, one might think that cronmight literally be a!ailable.

    While cron itsel& is not, An"roi" "oes ha!e a system ser!i'e name"

    6larm8anagerhi'h &ills a similar role. Bou gi!e it a tra steps, mostly stemming aroun" the 'on'ept o&the Wakeock.

    The 'a?e*ul$ntent"ervice Pattern

    Most times, i& you are bothering to get 'ontrol on a perio"i' basis, you illant to "o so e!en hen the "e!i'e is asleep. *or e>ample, i& you areriting an email 'lient, you ill ant to go get ne emails e!en i& the "e!i'eis asleep, so the user has all o& the emails imme"iately upon the ne>t timethe "e!i'e akes up. Bou might e!en ant to raise a 9otification base"upon the arri!e" emails.

    Alarms that ake up the "e!i'e are possible, but tri'ky, so e ill e>amine6larm8anagerin the 'onte>t o& this s'enario. An", to make that ork, e aregoing to use the WakefulIntentService O another o& the CommonsWare

    An"roi" Components, a!ailable as open sour'e &or you to use. n parti'ular,e ill be looking at the "emo proNe't &rom the WakefulIntentService

    '60

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    22/40

    ;vance "ervice Patterns

    ;it+ub proNe't,in a""ition to the implementation o& WakefulIntentServiceitsel&, spe'i&i'ally looking at these &rom the stan"point o& using6larm8anager&or s'he"ule" tasks.

    ote that to use WakefulIntentService you ill nee" the W6U:14CUpermission in your appli'ation, an" i& you are using the 6larmistenerapproa'h "es'ribe" in this 'hapter, you ill also nee" the=:C:IV:1744?1C48permission.

    Step 345 Create an Alar /istener

    8he WakefulIntentServiceo&&ers an 6larmistenerinter&a'e. & you 'reate one

    an" register it properly, theWakefulIntentService

    ill han"le mu'h o& the"etails o& arranging to s'he"ule your alarms hene!er they nee" to bes'he"ule", plus "o the a'tual perio"i' ork that you nee" the alarms &or.

    An 6larmistenernee"s to implement three metho"s

    sc0edule6larms!, hi'h is here you ill tea'h An"roi" hen analarm is suppose" to go o&&

    sendWakefulWork!, hi'h is here you tell WakefulIntentService

    hat shoul" o''ur hen an alarm goes o&& get8a%6ge!, here you in"i'ate ho long o& a time beteen alarms

    shoul" elapse be&ore WakefulIntentServiceassumes that the alarmsere lost an" nee" to be re-s'he"ule"

    *or e>ample, &rom the WakefulIntentService "emo proNe't, here is an6larmistenerimplementation name" 6ppistener

    packagecom.commonsware.cwac.wakeful.demo5

    importandroid.app.6larm8anager5importandroid.app.

  • 8/13/2019 Android Service Pattern

    23/40

    ;vance "ervice Patterns

    Conte%tct%t!; mgr.setIne(actRepeating6larm8anager.:61=:6?I8:1W6U:Ees o& "e'ision

    Do you ant the "e!i'e to ake up out o& sleep mo"e to per&ormthe taskJ

    Do you ant to spe'i&y the time &or the &irst task in terms o& a'tualreal orl" time, or simply an amount o& time &rom noJ

    '61

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    24/40

    ;vance "ervice Patterns

    8here are &our !alues, there&ore, you 'an 'hoose &rom &or the &irstparameter

    :61=:6?I8: in"i'ates you ant to spe'i&y a time relati!e toSstemClock.elapsed=ealtime!

    (a goo" 'hoi'e &or spe'i&ying a timerelati!e to no), an" you "o not ant to ake up the "e!i'e &or thealarms

    :61=:6?I8:1W6U:E'ept thatyou "o ant the "e!i'e to ake up out o& sleep mo"e

    =?C in"i'ates that you ant to spe'i&y a time relati!e toSstem.current?ime8illis! (a goo" 'hoi'e &or spe'i&ying a real-

    orl" time, as you 'an get a suitable !alue &or this out o& a CalendarobNe't), an" you "o not ant to ake up the "e!i'e &or the alarms

    =?C1W6U:E'ept that you "o ant the"e!i'e to ake up out o& sleep mo"e

    %o, in the abo!e sample, e are using setIne%act=epeating!, in"i'ating thate ant the &irst e!ent to o''ur one minute (50,000 millise'on"s) &romno, then re'ur e!ery 16 minutes or so.

    8he sendWakefulWork! metho" is here you in"i'ate toWakefulIntentService

    hat is to be "one hen ea'h alarm goes o&&. Mosttimes, you ill simply turn aroun" an" 'all sendWakefulWork! onWakefulIntentService itsel&, i"enti&ying your 'ustom sub'lass o&WakefulIntentService, here your business logi' ill resi"e. n the abo!esample, our business logi' is in 6ppService, hi'h e ill e>amine shortly.

    8he get8a%6ge!metho"... takes a bit o& e>plaining, hi'h e ill "o laterin this 'hapter. *or the moment, take it on &aith that a !alue o& ti'e yourperio" is a reasonable approa'h.

    Register the AlarReceiver

    8he WakefulIntentServicelibrary supplies a 'lass name" 6larm=eceiver. Bouill nee" to a"" this to your mani&est !ia a &receiver, element, to get

    '63

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    25/40

    ;vance "ervice Patterns

    'ontrol hen the "e!i'e akes up. *or e>ample, here is the mani&est &romthe "emo proNe't

    &'%mlversion()$.)encoding()utf-+)',&manifest%mlns/android()0ttp/""sc0emas.android.com"apk"res"android) package()com.commonsware.cwac.wakeful.demo) android/versionCode()G) android/version9ame()$.) android/installocation()auto),

    &uses-sdk android/minSdkVersion()O) android/targetSdkVersion()N)",

    &supports-screens android/largeScreens()false) android/normalScreens()true) android/smallScreens()false)",

    &uses-permissionandroid/name()android.permission.=:C:IV:1744?1C48) ", &uses-permissionandroid/name()android.permission.W6U:14CU)",

    &applicationandroid/label()2string"app1name), &receiverandroid/name()com.commonsware.cwac.wakeful.6larm=eceiver) , &intent-filter, &actionandroid/name()android.intent.action.744?1C48) ", &"intent-filter,

    &meta-data android/name()com.commonsware.cwac.wakeful) android/resource()2%ml"wakeful)", &"receiver,

    &serviceandroid/name().6ppService), &"service,

    &activit android/label()2string"app1name) android/name().>emo6ctivit) android/t0eme()2android/stle"?0eme.9o>ispla), &intent-filter, &actionandroid/name()android.intent.action.86I9)",

    &categorandroid/name()android.intent.categor.6E9C:=)", &"intent-filter,

    &"activit, &"application,

    &"manifest,

    Fur &receiver, points to the com.commonsware.cwac.wakeful.6larm=eceiver'lass an" ties it to a 744?1C48a'tion. 8his re?uires a &uses-permission,

    '65

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    26/40

    ;vance "ervice Patterns

    element to re?uest the =:C:IV:1744?1C48 permission, so users illkno at install time that e nee" to get 'ontrol hen the "e!i'e turns on.

    Fur &receiver,element also has a &meta-data,element. 8hese elements are

    use" to supply more in&ormation about a 'omponent than the mani&estIML 'alls &or. n our 'ase, e are in"i'ating that there is a""itional "ata,knon as com.commonsware.cwac.wakeful , a!ailable !ia a wakeful IMLresour'e ("res"%ml"wakeful.%ml). 8hat resour'e 'ontains a singleWakefulIntentServiceelement

    &WakefulIntentService listener()com.commonsware.cwac.wakeful.demo.6ppistener)",

    8he one attribute in that element, listener, points to our 6larmistenerimplementation &rom the pre!ious step.

    Step 365 $o 7our Wa*eful Wor*

    Fur 6ppService ill get 'ontrol in a metho" name" doWakefulWork!. 8hedoWakefulWork!metho" has similar semanti's to the onandleIntent!o& aregular IntentService O e get 'ontrol in a ba'kgroun" threa", an" the

    ser!i'e ill shut "on on'e the metho" returns i& there is no otheroutstan"ing ork. 8he "i&&eren'e is that WakefulIntentServiceill keep the"e!i'e aake hile doWakefulWork!is "oing its ork.

    n this 'ase, 6ppServiceNust logs a message to LogCat

    packagecom.commonsware.cwac.wakeful.demo5

    importandroid.content.Intent5importandroid.util.og5importcom.commonsware.cwac.wakeful.WakefulIntentService5

    publicclass6ppServicee%tendsWakefulIntentService ; public*ppService!; super)6ppService)!5 A

    24verride protectedvoiddo.a)eful.or)Intentintent!;

    '66

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    27/40

    ;vance "ervice Patterns

    og.i)6ppService)@)ITm awakeM ITm awakeM awn!)!5 AA

    An" that:s it. 8hose to steps O plus WakefulIntentServiceO is all you nee"to get 'ontrol on a perio"i' basis to "o ork, aking up the phone asnee"e".

    F& 'ourse, e ha!e not yet s'he"ule" any alarms. 8o un"erstan" ho to "othat, e nee" to &irst un"erstan" whento "o that.

    'hen Alarms Come and Go

    When your app is initially installe" by the user, none o& your 'o"e isimme"iately e>e'ute". +en'e, you ill not ha!e ha" a 'han'e to registerany alarms. %o, the &irst pla'e you nee" to think about registering youralarms is hen your laun'her a'ti!ity is e>e'ute". n theWakefulIntentService"emo, there is a >emo6ctivitthat "oes Nust that

    packagecom.commonsware.cwac.wakeful.demo5

    importandroid.app.6ctivit5importandroid.os.7undle5importandroid.os.Strict8ode5

    importandroid.widget.?oast5importcom.commonsware.cwac.wakeful.WakefulIntentService5

    publicclass>emo6ctivite%tends6ctivit ; 24verride publicvoidonCreate7undlesavedInstanceState!; super.onCreatesavedInstanceState!5

    Strict8ode.set+!readolicynewStrict8ode.?0read

  • 8/13/2019 Android Service Pattern

    28/40

    ;vance "ervice Patterns

    AA

    8he sc0edule6larms! metho" on WakefulIntentService takes an

    implementation o& your 6larmistener, a Conte%t, an" an optional boolean&lag in"i'ating hether or not the alarms shoul" be &or'e" to be s'he"ule",e!en i& they probably are alrea"y a'ti!e. y "e&ault, this is set to true,though our >emo6ctivithas it as false.

    %o, the &irst time your a'ti!ity is e>e'ute", the alarms ill be s'he"ule",&olloing the rules set "on in your 6larmistener. n an i"eal orl", this isall you oul" nee". & this ere an i"eal orl", though, this part o& the book

    oul" not nee" to be ritten. %in'e you are rea"ing it, you 'an tell that this

    is not an i"eal orl".

    %o, hen else "o e nee" to s'he"ule alarmsJ

    +n a Reboot

    A $ni>-style 'ron "aemon ill pi'k up Nobs here it le&t o&& a&ter a reboot.%imilarly, Win"os G%'he"ule" 8asksG ill resume a&ter a reboot.

    Fn the other han", 6larm8anagerin An"roi" is ipe" 'lean, starting ithero s'he"ule" alarms. 8he argument that e ha!e been gi!en is that the'ore An"roi" team "oes not ant apps to s'he"ule alarms an" G&orgetGabout them, 'ausing them to pile up an" slo "on the "e!i'e. While thisis a noble obNe'ti!e, it "oes 'ause some annoyan'e, as e nee" to get'ontrol at boot time an" arrange to res'he"ule the alarms.

    After )eing Force,Stopped

    $sers 'an go into the %ettings appli'ation, &in" your appli'ation, an" 'li'k aG*or'e %topG button. When they "o this, your app mo!es into a Gstopppe"Gstate. othing o& your 'o"e ill run again O in'lu"ing any 7roadcast=eceiver'omponents that you ha!e "e&ine" O until the user proa'ti!ely runs one o&

    your a'ti!ities again, typi'ally &rom the laun'her. +en'e, any user that

    '78

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    29/40

    ;vance "ervice Patterns

    &or'e-stops your app ill 'ause you to not re'ei!e any s'he"ule" alarmse!er again, as the e>isting alarms are remo!e" an" you ill not be able toget 'ontrol again at boot time.

    8his is hy e are looking at s'he"uling the alarms e!ery time the>emo6ctivit runs. ot only might it be the !ery &irst time the user haslaun'he" our a'ti!ity, but it might be the !ery &irst time the user haslaun'he" our a'ti!ity a&ter being &or'e-stoppe".

    *ortunately, WakefulIntentServicehan"les these s'enarios &or you, so longas you 'all sc0edule6larms!hene!er your app is laun'he". 8his is hereget8a%6ge!'omes into play O i& WakefulIntentService"ete'ts that an alarmhas not gone o&& in the number o& millise'on"s you return &rom

    get8a%6ge!, it assumes that the user &or'e-stoppe" your appli'ation an" its'he"ules the alarms again.

    The :'a?e*ul: o* 'a?e*ul$ntent"ervice

    o, let us take a look Gun"er the 'o!ersG to see ho WakefulIntentServicea'tually keeps the "e!i'e aake long enough &or doWakefulWork!to "o its,um, ake&ul ork.

    Concept of Wa*e/oc*s

    Most o& the time in An"roi", you are "e!eloping 'o"e that ill run hilethe user is a'tually using the "e!i'e. A'ti!ities, &or e>ample, only reallymake sense hen the "e!i'e is &ully aake an" the user is tapping on thes'reen or keyboar".

    #arti'ularly ith s'he"ule" ba'kgroun" tasks, though, you nee" to bear in

    min" that the "e!i'e ill e!entually Ggo to sleepG. n &ull sleep mo"e, the"isplay, main C#$, an" keyboar" are all poere" o&&, to ma>imie batteryli&e. Fnly on a lo-le!el system e!ent, like an in'oming phone 'all, illanything ake up.

    '7/

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    30/40

    ;vance "ervice Patterns

    Another thing that ill partially ake up the phone is an Intentraise" bythe 6larm8anager. %o long as broa"'ast re'ei!ers are pro'essing that Intent,the 6larm8anagerensures the C#$ ill be running (though the s'reen an"keyboar" are still o&&). Fn'e the broa"'ast re'ei!ers are "one, the

    6larm8anagerlets the "e!i'e go ba'k to sleep.

    Bou 'an a'hie!e the same e&&e't in your 'o"e !ia a Wakeock, obtaine" !ia thet &e se'tions.

    The Wa*e/oc* Proble

    *or a 1W6U:Ee'uting. *or some situations, that may be all that is nee"e".+oe!er, on=eceive!is 'alle" on the main appli'ation threa", an" An"roi"

    ill kill o&& the re'ei!er i& it takes too long.

    Bour natural in'lination in this 'ase is to ha!e the 7roadcast=eceiverarrange &or a Serviceto "o the long-running ork on a ba'kgroun" threa",sin'e 7roadcast=eceiverobNe'ts shoul" not be starting their on threa"s.#erhaps you oul" use an IntentService, hi'h pa'kages up this Gstart aService to "o some ork in the ba'kgroun"G pattern. An", gi!en thepre'e"ing se'tion, you might try a'?uiring a partial Wakeock at thebeginning o& the ork an" release it at the en" o& the ork, so the C#$ illkeep running hile your IntentService"oes its thing.

    8his strategy ill ork...some o& the time.

    '7'

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    31/40

    ;vance "ervice Patterns

    8he problem is that there is a gap in Wakeock'o!erage, as "epi'te" in the&olloing "iagram

    #igure 3/2 The Wake)ock gap

    8he 7roadcast=eceiver ill 'all startService! to sen" ork to theIntentService, but that ser!i'e ill not start up until a&ter on=eceive!en"s.

    As a result, there is a in"o o& time beteen the en" o& on=eceive!an"hen your IntentService'an a'?uire its on Wakeock. During that in"o,the "e!i'e might &all ba'k asleep. %ometimes it ill, sometimes it ill not.

    What you nee" to "o, instea", is arrange &or o!erlapping Wakeockinstan'es.Bou nee" to a'?uire a Wakeock in your 7roadcast=eceiver, "uring theon=eceive! e>e'ution, an" hol" onto that Wakeock until the ork is'omplete" by the IntentService

    '70

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    32/40

    ;vance "ervice Patterns

    #igure 3'2 The Wake)ock overlap

    8hen you are assure" that the "e!i'e ill stay aake as long as the orkremains to be "one.

    Wa*efulIntentService and Wa*e/oc*s

    y no, you ha!e noti'e" that the WakefulIntentService re'ipe "oes notha!e you manage your on Wakeock. 8hat is be'ause WakefulIntentServicehan"les it &or you. Fne reason hy WakefulIntentServicee>ists is to managethat Wakeock, be'ause Wakeockssu&&er &rom one maNor problem they are

    not tra. +en'e,&or our 7roadcast=eceiver an" our WakefulIntentService to use the sameWakeock, they ha!e to be share" !ia a stati' "ata member... hi'h is i'ky.WakefulIntentServiceis "esigne" to hi"e this i'ky part &rom you, so you "onot ha!e to orry about it.

    $nside 'a?e*ul$ntent"ervice

    With all that behin" us, no e 'an take a look at some pie'es o& hoWakefulIntentServiceper&orms its magi'.

    '7&

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    33/40

    ;vance "ervice Patterns

    scheduleAlars-.

    Fur >emo6ctivit'alle" sc0edule6larms!. 8he Nob o& sc0edule6larms!is toget your 6larmistenerto s'he"ule the alarms, i& it appears that this is

    ne'essary

    publicstaticvoidsc!edule*larms6larmistenerlistener@ Conte%tct%t!; sc!edule*larmslistener@ct%t@true!5A

    publicstaticvoidsc!edule*larms6larmistenerlistener@ Conte%tct%t@ booleanforce!; S0ared

  • 8/13/2019 Android Service Pattern

    34/40

    ;vance "ervice Patterns

    8he "onsi"e o& alays s'he"uling the alarms is that i& you useset=epeating!, the alarm ill ne>t go o&& at your "esignate" time, hi'hmay be &ar sooner than the e>isting alarm oul" 'all &or. *or e>ample,suppose that you ant to get 'ontrol on'e per "ay. & you 'all

    set=epeating!or setIne%act=epeating!e!ery time the user laun'hes yourmain a'ti!ity, you ill trigger the alarm to go o&& ea'h o& those times, ina""ition to the on'e per "ay. $sing set=epeating!ith a spe'i&i' time o&the "ay (e.g., /am) ill not ha!e that e&&e't, but set=epeating!ith G"o the&irst one a minute &rom noG oul".

    AlarReceiver

    8he WakefulIntentService-supplie" 6larm=eceiverill get 'ontrol hen the

    "e!i'e poers on (!ia our mani&est entry) an" hen the alarm goes o&&. Atthose times, on=eceive!ill be 'alle"

    24verride publicvoidonReceiveConte%tct%t@Intentintent!; 6larmistenerlistener(getListenerct%t!5

    iflistenerM(null!; ifintent.get*ction!((null!; S0ared

  • 8/13/2019 Android Service Pattern

    35/40

    ;vance "ervice Patterns

    null, that means e are being starte" &rom the 744?1C48broa"'ast, inhi'h 'ase e 'all sc0edule6larms!on your 6larmistener.

    Where "oes the 6larmistenerobNe't 'ome &romJ A pri!ate getistener!

    metho" that takes a"!antage o& the &meta-data,&rom the mani&est

    2Suppress.arnings)unc0ecked)!privateWakefulIntentService.6larmistenergetListenerConte%tct%t!;

  • 8/13/2019 Android Service Pattern

    36/40

    ;vance "ervice Patterns

    returnnull!5A

    8o rea" "ata &rom a &meta-data, element, you use ata! metho",hi'h returns an ml=esource

  • 8/13/2019 Android Service Pattern

    37/40

    ;vance "ervice Patterns

    @ither &la!or o& sendWakefulWork!on WakefulIntentServicee!entually routesto a getock!metho"

    staticfinalString968:()com.commonsware.cwac.wakeful.WakefulIntentService) 5staticfinalString6S?166=8()last6larm)5privatestaticvolatile

  • 8/13/2019 Android Service Pattern

    38/40

    ;vance "ervice Patterns

    Wakeockinstan'es to ensure 'onstant 'o!erage as you pass &rom 'omponentto 'omponent.

    o, our ser!i'e ill start up an" be able to "o something, hile the C#$ is

    running "ue to our a'?uire" Wakeock.

    %o, WakefulIntentService ill no get 'ontrol, un"er an a'ti!e Wakeock.%in'e it is an IntentServicesub'lass, onandleIntent! is 'alle". +ere, e

    Nust route 'ontrol to the sub'lass: implementation o& an abstra'tdoWakefulWork! metho", ensuring that e release the Wakeockhen the

    ork is "one, e!en i& a =untime:%ceptionis raise"

    24verride

    finalprotectedvoidon,andleIntentIntentintent!; tr; do.a)eful.or)intent!5 A finall; getLoc)t0is.get*pplicationConte(t!!.release!5 AA

    As a result, ea'h pie'e o& ork that gets sent to the WakefulIntentServiceill a'?uire a Wakeock!ia sendWakefulWork!an" ill release that Wakeockhen doWakefulWork!en"s. Fn'e that Wakeockis &ully release", the "e!i'e'an &all ba'k asleep.

    Bac?#round Data "ettin#

    $sers 'an 'he'k or un'he'k a 'he'kbo> in the %ettings appli'ation thatin"i'ates i& they ant appli'ations to use the nternet in the ba'kgroun".%er!i'es employing 6larm8anagershoul" honor this setting.

    8o &in" out hether ba'kgroun" "ata is alloe", use theConnectivit8anagersystem ser!i'e an" 'all get7ackground>ataSetting! . *ore>ample, your alarm-triggere" 7roadcast=eceiver 'oul" 'he'k this be&orebothering to arrange &or the IntentService(or WakefulIntentService) to "o

    ork.

    088

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    39/40

    ;vance "ervice Patterns

    Bou 'an also register a 7roadcast=eceiver to at'h &or the6C?I49176CU#=4E9>1>6?61S:??I9#1C69#:> broa"'ast, also "e&ine" onConnectivit8anager. *or e>ample, you 'oul" ele't to 'ompletely 'an'el youralarm i& the ba'kgroun" "ata setting is &lippe" to false.

    The DEverlasting "erviceD ;nti$Pattern

    Fne anti-pattern that is all too pre!alent in An"roi" is the Ge!erlastingser!i'eG. %u'h a ser!i'e is starte" !ia startService!an" ne!er stops O the'omponent starting it "oes not stop it an" it "oes not stop itsel& !iastopSelf!.

    Why is this an anti-patternJ 8he ser!i'e takes up memory all o& the time. 8his is ba" in its on

    right i& the ser!i'e is not 'ontinuously "eli!ering su&&i'ient !alue tobe orth the memory.

    $sers, &earing ser!i'es that sap their "e!i'e:s C#$ or AM, mayatta'k the ser!i'e ith so-'alle" Gtask killerG appli'ations or mayterminate the ser!i'e !ia the %ettings app, thereby "e&eating youroriginal goal.

    An"roi" itsel&, "ue to user &rustration ith sloppy "e!elopers, illterminate ser!i'es it "eems ill-use", parti'ularly ones that ha!e run&or ?uite some time.

    F''asionally, an e!erlasting ser!i'e is the right solution. 8ake a F# 'lient,&or e>ample. A F# 'lient usually nee"s to hol" an open so'ket ith the

    F# ser!er to kno about in'oming 'alls. 8he only ay to 'ontinuouslyat'h &or in'oming 'alls is to 'ontinuously hol" open the so'ket. 8he only'omponent 'apable o& "oing that oul" be a ser!i'e, so the ser!i'e oul"

    ha!e to 'ontinuously run.

    +oe!er, in the 'ase o& a F# 'lient, or a musi' player, the user is the onespe'i&i'ally re?uesting the ser!i'e to run &ore!er. y usingstartoreground!, a ser!i'e 'an ensure it ill not be stoppe" "ue to ol" age&or 'ases like this.

    08/

    http://commonsware.com/AdvAndroid

    Free excerpt from _The Busy Coder's Guide

    to Advanced Android Development_.

    Copyright (c) 2011 CommonsWare, LLC.

    All Rights Reserved

  • 8/13/2019 Android Service Pattern

    40/40

    ;vance "ervice Patterns

    As a 'ounter-e>ample, imagine an email 'lient. 8he 'lient ishes to 'he'k&or ne email messages perio"i'ally. 8he right solution &or this is the6larm8anager pattern "es'ribe" earlier in this 'hapter. 8he anti-pattern

    oul" ha!e a ser!i'e running 'onstantly, spen"ing most o& its time aiting

    &or the polling perio" to elapse (e.g., !ia ?0read.sleep!). 8here is no !alueto the user in taking up AM to at'h the 'lo'k ti'k. %u'h ser!i'es shoul"be reritten to use 6larm8anager.

    Most o& the time, though, it appears that ser!i'es are simply leake". 8hat isone a"!antage o& using 6larm8anageran" an IntentServiceO it is "i&&i'ult toleak the ser!i'e, 'ausing it to run in"e&initely. n &a't, IntentService ingeneral is a great implementation to use hene!er you use the 'omman"pattern, as it ensures that the ser!i'e ill shut "on e!entually. & you use a

    regular ser!i'e, be sure to shut it "on hen it is no longer a'ti!ely"eli!ering !alue to the user.

    http://commonsware.com/AdvAndroid