26
Communicating with a Server

Communicating with a Server · 2017. 6. 7. · COMP 107x (Muppala) Android Networking 2 Database Server Client-server communication Backend HTTP with REST API. The Networking Alphabet

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

  • CommunicatingwithaServer

  • TheCloud

    ClientandServer• Mostmobileapplicationsarenolongerstand-alone• Manyofthemnowhavea“Cloud”backend

    COMP107x(Muppala) AndroidNetworking 2

    DatabaseServerBackendClient-servercommunication

    HTTPwithRESTAPI

  • TheNetworkingAlphabetSoup

    COMP107x(Muppala) AndroidNetworking 3

    HTTPURL JSONXMLSOAP RESTGETPOST PUT

  • AndroidNetworking• Networkoperationscauseunexpecteddelays• Alwaysdonetworkoperationsinthebackground– UseAsyncTask()orbackgroundthread– AndroidwillcauseexceptionifyoudonetworkingoperationsonthemainUIthread

    COMP107x(Muppala) AndroidNetworking 4

  • Offtothenextexercise• ProcessingaJSONstring• MappingJSONstringtoJavaObjects• UsingGson library

    COMP107x(Muppala) AndroidNetworking 5

  • Javascript ObjectNotation(JSON)

  • HTTPResponse• Servermaysendbackinformation inaspecificformat:

    – eXtensible MarkupLanguage(XML)– Javascript ObjectNotation(JSON)

    • Android alsoincludesthreeparsersforXMLandaparserforJSON– thetraditionalW3CDOMparser(org.w3c.dom)– convertsdocumenttoatreeofnodes– aSAXparser(org.xml.sax)– streamingwithapplicationcallbacks– theXMLpullparser– iteratesoverXMLentries– JSONparser(org.json)

    • Alsoconsider theuseofthird-partylibrariestodealwithspecificformatslikeRSS/Atomparser

    • Gson librariestoconvertfromJavaobjectstoJSONandback

    COMP107x(Muppala) AndroidNetworking 7

  • Javascript ObjectNotation(JSON)• http://www.json.org• Lightweightdatainterchange format• Languageindependent*• Self-describingandeasytounderstand• Datastructuredas:

    – Acollectionofname/valuepairs– Orderedlistofvalues– Example

    {"people":[{"id":1,"name":"John”,"statusMsg": "Imagineallthepeople...”,"imageURL":"John.png”},{"id":2,"name":"Paul”,"statusMsg": "Letitbe...”,"imageURL":"Paul.png”},{"id":3,"name":"George”,"statusMsg": "Waitmisterpostman...”,"imageURL":"George.png" },{"id":4,"name":"Ringo”,"statusMsg": "Yellowsubmarine...”,"imageURL":"Ringo.png”}

    ]}

    COMP107x(Muppala) AndroidNetworking 8

  • Offtothenextexercise• UsinganAsyncTask tooffloadworkfromthemainUIthread

    • UsingPicassoimagedownloadinglibrary

    COMP107x(Muppala) AndroidNetworking 9

  • AsyncTask:DoingWorkintheBackground

  • Threads/AsyncTask

    COMP107x(Muppala) AndroidNetworking 11

    UIThread BackgroundThread

    Spawnbackground threadorUseAsyncTask

    ReturnresultToupdateUICodeto

    RunonUIthread

  • AsyncTask• Threadsprovidesapowerfulframework– Codegetscomplicatedanddifficulttoread

    • AsyncTask:simplifiesthecreationoflong-runningtasksthatneedtocommunicatewiththeUI– Takescareofthreadmanagement– HastobecreatedontheUIthread

    COMP107x(Muppala) AndroidNetworking 12

  • AsyncTask• AsyncTask hasthefollowingexcellentfeatures:– Abilitytoreturnvalues ofcustomtypetotheUIthreadwhenthetaskisfinished

    – AbilitytoexecutesomecodeintheUIthread beforethebackgroundtaskbeginsexecutionandafteritisfinished

    – Abilitytopushupdates totheUIthreadduringtheexecutionofthebackgroundtask

    – Automatic under-the-hoodthreadmanagement

    COMP107x(Muppala) AndroidNetworking 13

  • AsyncTask Exampleprivate class WorkerTask extends AsyncTask {

    //InitializetheprogressbarandthestatusTextView@Overrideprotected void onPreExecute() {

    completed =0;//ThiswillresultinacalltoonProgressUpdate()publishProgress();

    }

    @Override//ThismethodupdatesthemainUI,refreshing theprogress barandTextView.protected void onProgressUpdate(String... values){

    }

    //Dothemaincomputation inthebackgroundandupdatetheUIusingpublishProgress()@Overrideprotected Boolean doInBackground(Object...params){

    return null;}

    }COMP107x(Muppala) AndroidNetworking 14

  • AsyncTask• SeveralmethodsarepartofAsyncTask:

    – doInBackground()executesautomaticallyonaworkerthread– onPreExecute(),onPostExecute(),andonProgressUpdate()areall

    invokedontheUIthread– CallpublishProgress()atanytimeindoInBackground()toexecute

    onProgressUpdate()ontheUIthread– ThevaluereturnedbydoInBackground()issenttoonPostExecute()– Youcancancelthetaskatanytime,fromanythread

    COMP107x(Muppala) AndroidNetworking 15

  • Offtothenextexercise• ConnectingtoaserverusingHTTPURLconnection

    • GettingJSONstringfromtheserver

    COMP107x(Muppala) AndroidNetworking 16

  • AndroidNetworking

  • AndroidPermissions• SetpermissionintheManifestfile:

    COMP107x(Muppala) AndroidNetworking 18

  • AndroidConnectivityManager• AndroidprovidestheConnectivityManagerclasstomonitornetworkconnectivitystate,settingpreferrednetworkconnectionsandmanagingconnectivityfailover

    • GetaccesstotheConnectivityManager by:ConnectivityManagermyNetMan =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    COMP107x(Muppala) AndroidNetworking 19

  • AndroidConnectivityManager• ConnectivityManagerprovidesmethodslikegetNetworkInfo(),getActiveNetworkInfo(),andgetAllNetworkInfo()etc.– ThesemethodsreturntheNetworkInfo object– CanusemethodswithinthisobjectlikeisAvailable(),isConnected,isConnectedorConnecting(),getState(),etc.

    COMP107x(Muppala) AndroidNetworking 20

  • AndroidConnectivityManager• Ifyouareusingthenetworkaccessinyourapplication,itisalwaysagoodideatocheckifthe

    networkconnectivityexists,andtakeactionaccordingly• Example

    public boolean isOnline() {ConnectivityManager connMgr =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo =connMgr.getActiveNetworkInfo();

    if(networkInfo !=null&&networkInfo.isConnected()) {returntrue;

    }else{returnfalse;

    }}

    COMP107x(Muppala) AndroidNetworking 21

  • AndroidHTTPSupport

  • AndroidandHTTP• AndroidprovidesHTTPURLConnection clienttosendandreceive

    dataovertheweb• AndroidalsohasApacheHTTPcomponentslibrarybuiltintothe

    framework– HttpClient componentenableshandlingofHTTPrequestsonyour

    behalf,issuingHTTPrequestsanddealingwiththeresponse– Notthepreferredchoiceanymore

    • YoucanlayeraSOAP/XML-RPClayeratopthislibraryoruseit"straight"foraccessingREST-stylewebservices

    COMP107x(Muppala) AndroidNetworking 23

  • AndroidHTTPURLConnection ExamplefinalStringsite="http://:3000/people";

    //gettheURLconnectionURLurl =newURL(site);HttpURLConnection urlConnection =(HttpURLConnection)url.openConnection();

    //setup theURLrequestparametersurlConnection.setReadTimeout(10000/*milliseconds*/);urlConnection.setConnectTimeout(15000 /*milliseconds*/);urlConnection.setDoInput(true);

    /*optionalrequestheader*/urlConnection.setRequestProperty("Content-Type", "application/json");urlConnection.setRequestProperty("Accept", "application/json");

    /*forGetrequest*/urlConnection.setRequestMethod("GET");

    COMP107x(Muppala) AndroidNetworking 24

  • AndroidHTTPURLConnection Example//Startsthequeryint statusCode =urlConnection.getResponseCode();Log.d(DEBUG_TAG,"Theresponseis:"+statusCode);

    //getthe inputstreamfortheresponsebodyoftheURLresponseInputStream inputStream =new

    BufferedInputStream(urlConnection.getInputStream());

    //parsetheresponseStringresponse=convertInputStreamToString(inputStream);parseResult(response);

    COMP107x(Muppala) AndroidNetworking 25

  • Assignment5:AsynchronousDownloadofImages

    • UsePicassolibrarytodownloadtheimagesasynchronouslyandupdatetheListViewavatarsoftheusers

    COMP107x(Muppala) AndroidNetworking 26