You are on page 1of 7
sro Consume Webservice in Andria using irtentService | Surviving wi Android Surviving w/ Android Android develop ‘utorials about Andr OVVOO Consume Webservice In Android Using IntentService ss nt pos xi how consume Reber usin, Weloon ne | Tapes cover Corto Scouse ninesng empty orang, |, fe covers We know that Andvois Service nas 2 longer Ife than an Andtaid Acti and we want 2 asks completed even Fz app ULis no longer avalable me snl use a Serce. We can consider for_| Rest Webservice example the download scenarc: t's suppose we want to download sore information frm 3 remote server: we can do tin the UI (.e Activity) but the user, fr example moves to anther pp the donnload wil be inerupted fe want tobe sure that he downloas continues event | paguRecsivee the app isnt anymore ative we can use Service, IntentService Description When we wancto consume a Webservice, we hve tobe aware that the time requted fo contac the Server and get he response ‘an be quite long, Even f we execute ths lage sa Separate servic, the serie ise rns in the main thread, tha the cling, tity cantag alin forthe response from the service, and tne OS can kil showing the annoying ANR message, We con avoid ths problem handling a separate thread nse the service, but Andrld OX provides 2 speclzed cls, derived fom the Service class called intensSerice defines as (om Android 1 docs: “ntentSorice ia base cas for Servtces that handle asynchronous requests expressed as Intents} an demand, Clients snd request through storeService(Zntent) calls the service is strtd as needed handles each Intentin turn using a worker hea, ad stops tse when runs out of work This work queue processor" pattern Is commonly used to offload tasks rom an ‘pplication’ main tread Considering that the heavy works made na separate thread we dont know when itl shane he cling ett is unaware oft We il describe now to get back the information asthe seruce eeved data rom the remate Webservice, Creating The IntentService ‘As example we wll use Yanoo! Finance Servet retrieve te curren Ask nd Bid vale fora Stock At the end we wll bul a app Iie e Android Restful Service ipihwww suvivingatbancie.com2014#03icorsume-webservice-in-andrid-rtentserviceHiml ‘you find this Hog sel lar dd 61 the Dg and sharelt ata Popul Poste w sro Consume Webservice in Andria using irtentService | Surviving wi Android The fies step is creating serve public class quoteservice extenés intentservice { override protected void ontandierntent( intent intent) { Attine in BrHGRaTETAEEREve do the neany work’, so we calhe remote Webservice and parse the response. In thi case we an simply use XmPulParse to parse the date 11 Were we retrseve the stock que tog.c¢"sev", “Get stock"); String url + YAHOO FINANCE URL. replaceAlL(“Asyne", stock. getSymbol()); HetpuaLconnection con = (ittpURl Connection) ( new URL(uP3)) openCennection(); con. setRequestiethoa 6 ton. comect0) = con. getinpusstrean() 11 Start parsing 2 youllParser parser = xnlpullvarserractory.neutastance() -rewoullParser(); parser.setinput(1s, null): nt event = parser gotiventtype()s string tagtane ~ mill; while (event l= XalPullbarser.€N® DOCUMENT) { faghane = parser. gethane(); Log.d(*Sev", Tags” + taptane) 46 (event == 2elPullParser-START_TAG) { ‘current Tag = taghane: flse 46 (event == xPullParser. TEXT) ( 3€-(CASK" equalstgrorecase(currentT36)) We else if (°810"-equslstgnorecase(currenttag)) ( a > ? event = parser.next(s catch (Exception e) ( sprinestackinace(); Then we define our servic inthe Manfes.xm ceervice androsdsnane=" quateservice” /> Activity: Webservice Client ‘The nex steps creating the cline activity tht invokes the servic, Weare using an Intent Serve then the calling Activity calle he service anc then forget The acy suite tv because ae soon asthe usr eck Get quote” Button we invoke the service use startservice( service intent): Anyway there are two aspects we should consider: 1. How we poss the data tothe service ipihwww suvivingatbancie.com2014#03icorsume-webservice-in-andrid-rtentserviceHiml expense! sro Consume Webservice in Andria using intentService | Surviving wi Android 2. How we get the data back fom the service and show the information in UL Topass data tothe service we can creat a simple ava less that hold the stock symbol an the values we want to be ile by the Service as we get the response. Our dass should be a Paeelable dass public class stock inplenents Parcelable { private string symbol; private double askvalue; private double bivalve; public stock) (2 public Stock(String syebol, double asivatue, double biavatue) { 11 get and set method Qoverride el(parcel dest, int flags) ¢ 11 We write the stock information in the parcel destowritestring(syabol); dest wrstedouble(askva2ue); dese wrsteDeuble(oidvenue); > public static final creatore o> CREATOR = naw Creatorcstock>() { eoverrsee public Stock createfronparcel(Parcel source) ( Stock stoee = new Stock()3 stock. retSynbol (sour .readstrng()); Stock. setarkvaiue(soures. readbouble()); stock setbidValue( source, readboubie())3 > eoverriae public Stock{] nawkeray(int size) ( return new St0ck[ 8]; } override public int deseribecontents() { Atle 18 and 25, we implement the two methods required to marshal and unmarshal our lass, Retrieve Data From Service Using ResultReceiver Another Interesting aspects now we can get the values back rom the intetService, AS we, lead know the callng acy doesnt wae forthe result, s0 we have to find another way. Generally speaking there ae diferent ways to solv ths problem in this post wil expan how to use ResulRecelve. Tis methods quite simple and elegant in my opinion. The est steps creating a lass that extends Resulecever, that we callQuateserviceReceivar} public class quoteserviceReceiver extends Rest ceiver ( public quoteserviceReceiver(Handler handler) { super(hanaler); public void setListenee(Listener Listener) { > override ipihwww suvivingatbancie.com2014#03icorsume-webservice-in-andrid-rtentserviceHiml sro Consume Webservice in Andria using irtentService | Surviving wi Android 4+ (aistener t= null) pata) < esultcode, resultData); } public static interface Listener { void onkeceivetesult(snt resultCode, uncle resultbats); ? ‘This class very simple. A ne 19 e define an interface that he cling activ hasta implement to get ntfied when the data Isavallable Inns intrface we define» Bunce that olds the data retrieved, Then a line 4 we overide the oneceiveesl nd call ou callback method defined in the previous interface. From the lent point of view(s ou Activity we simply have to implements the interface defined an pass the QuoteSeruceRecever tothe ntenserice private Intent creat stock) ¢ Treent 4'= new Intert(tnis, Quoteservice.cl25s); ‘quoteserviceneceiver receiver ~ new Quoteserviceteceiven(new Handler(}); receiver setlistener(tis); Eiputexteatree’, receiver); Siputextra("stock”, tock); and when we cll the serie: starsService(crentecalLingintent(stoc8))3 and in he callback method override Public void onecelvenesult{int resultCode, Bundle result0ata) { Stock stock = resultData.gotParcelable("steck”); Leg.a("Sew", “Stace (stock )*) astvaluesetText("" + stock. getAskvalue()): DlovaluecsetTexe("” + stock getaidvalue()): an here we update the UL wh the dara eceved inthe service tat consumes the remate Webservice override protected void onkandletntent(rntert intent) ( Stock stock = intent. getParcelablesstra( stock"); Final aesultheceiver rec = (ReseltReceiver) intent getParcelabletxtra(*ree")s U7 tren data 4s ready sf (OID equalstgnorecase(currentTag)) { stockfesult. setaidvaive(ouble.panseDouble(parser.getText())): dundie b= new Bundle(); B.putParcelable( stock", stockResult) rec-send(®, 8); Source code avaiable github {You might be interested on: [andra Service Tutorial [andrei Bound Service: IPC with Messenger 2 comments entered ans weber eae, rest erect bee ipihwww suvivingatbancie.com2014#03icorsume-webservice-in-andrid-rtentserviceHiml sarote 2.comments Justa smallrosb question. servic. Itink we stil Quite informative. Wet done Android WeatherLib: A new i Weather App easily and fast to create Android — ie svange. Aryay IMO you fveryting under lb media, When you creat thie ‘Android SwipeRefreshLayout Tutorial = Instead of acing an onSerolitene, you shoud such the SwipeRefesh yout clas and Over he Suber to: Poet amen atom) Consume Webservice in Anérold using IrtentService | Surviving wi Andros hy do you tink wo can nat use AsyreTask ogo the stock quces from server stead of th response even when the ap is miniized. Pease ley ‘Android app development -weather app with forecast = Welles stp you have to [Android ListView: Endiess adaptor = @dcciveoge | agree with you anya sing Endlosstaptor i 1.080.000" ms ipihwww suvivingatbancie.com2014#03icorsume-webservice-in-andrid-rtentserviceHiml arose TT Consume Webservice in Anrold using Intent Service | Suvi¥ing wi Android ‘ges Reserved, Reproduction without expt petmision's probe, Develop aero wester ap ith Matera Design narod prorated actions: Fesing acon buton FB) narod iw vith mel rom yu soarodRegeterien cent Posts Wet by Helou Deg arene > ocober) > gest) > yen > ne > apa nord Rete Serve TtorabADL-hom a tet > Febery 2) > january 2) rae Ts Fell sik O@OoO® Fw wy al nari view Custom Fite and terse interface nie peu ste stowed fe nay we ca roparig Clan CE, 2057, Donon, Up, nid enter app J50N, HTT a Topics coveres How cevel narid Usvew: Custom Adapter a Viele As AS een ra Alpert you Opis ipuhwww survivingatbancie.com/2014#03\corsume-webservice-in-andrid-rtentserviceHiml sro Consume Webservice in Andria using intentService | Surviving wi Android Topi cove Ani Speehlayat eras Listen Rees Spt Fjpe Anatole Wester app Toor: Step by Sep ule art 2) 15% Tapes coverec andra Wether op Yana Wenher len ra ML Par ipihwww suvivingatbancie.com2014#03icorsume-webservice-in-andrid-rtentserviceHiml am

You might also like