Android App Development 06 : Network & Web Services


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Android App Development 06 : Network & Web Services

  1. 1. 6 Network & Web Services Anuchit Chalothorn anoochit@gmail.comLicensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
  2. 2. Connecting to NetworkNote that to perform the network operationsdescribed in this lesson, your applicationmanifest must include the following permissions:<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>Ref:
  3. 3. StrictModeWithin an Android application you should avoidperforming long running operations on the userinterface thread. This includes file and networkaccess. StrictMode allows to setup policies inyour application to avoid doing incorrect things.
  4. 4. Turn StrictMode OffIf you are targeting Android 3.0 or higher, you can turn thischeck off via the following code at the beginning of youronCreate() method of your Activity. (Not recommend)StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);
  5. 5. Manage Network UsageA device can have various types of network connections.This lesson focuses on using either a Wi-Fi or a mobilenetwork connection. To check the network connection, youtypically use the following classes:● ConnectivityManager: Answers queries about the state of network connectivity. It also notifies applications when network connectivity changes.● NetworkInfo: Describes the status of a network interface of a given type (currently either Mobile or Wi-Fi).
  6. 6. Check the Network ConnectionConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo=connMgr.getActiveNetworkInfo();if (networkInfo != null && networkInfo.isConnected()){ // fetch data} else { // display error}
  7. 7. Workshop: Check network connectionUse snippet from previous slide to checknetwork connection and notify user.ConnectivityManager connMgr = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
  8. 8. Network Operations on a Separate ThreadNetwork operations can involve unpredictabledelays. To prevent this from causing a pooruser experience, always perform networkoperations on a separate thread from the UI.The AsyncTask class provides one of thesimplest ways to fire off a new task from the UIthread.
  9. 9. AsyncTaskThe AsyncTask class provides one of thesimplest ways to fire off a new task from the UIthread.private class DownloadWebpageText extends AsyncTask { protected String doInBackground(String... urls) { ... }}
  10. 10. Workshop: Read text data from webRead HTML data from web usingHTTPConnection. See snippet in GitHub.
  11. 11. Workshop: Load Image from WebRead stream binary from web and pass intoImageViewInputStream in = new URL(url).openStream();myImage = BitmapFactory.decodeStream(in);imageView.setImageBitmap(myImage);
  12. 12. Web ServicesA web service is a method of communicationbetween two electronic devices over the WorldWide Web. We can identify two major classesof Web services ● REST-compliant Web services ● arbitrary Web services.
  13. 13. SOAP: Old fasion Yellow Pages WSDL WSDL WSDL Requester Provider SOAPRequester ask or search yellow pages which address and how to talk with provider. The yellow pages ll send the response by using WSDL how to talk which provide by Provider to the requester. Requester receives the address and methods then communicate with Provider.
  14. 14. Web APIsA web API is a development in web serviceswhere emphasis has been moving to simplerrepresentational state transfer (REST) basedcommunications. RESTful APIs do not requireXML-based web service protocols (SOAP andWSDL) to support their light-weight interfaces.
  15. 15. API ProtocolsRef:
  16. 16. Data FormatsRef:
  17. 17. Say "Goodbye" to XML
  18. 18. RESTFul / REST APIa style of software architecture for distributedsystems such as the WWW. The RESTlanguage uses nouns and verbs, and has anemphasis on readability. Unlike SOAP, RESTdoes not require XML parsing and does notrequire a message header to and from aservice provider.
  19. 19. Concept● the base URI for the web service, such as● the Internet media type of the data supported by the web service.● the set of operations supported by the web service using HTTP methods (e.g., GET, PUT, POST, or DELETE).● The API must be hypertext driven.
  20. 20. HTTP Request HTTP Request Client Server HTTP Response + Data 200 OK 403 Forbidden 404 Not found 500 Internal Error
  21. 21. HTTP Request GET /users/anoochit HTTP/1.1 Requester Provider 200 OK + Data
  22. 22. Example URI●●●
  23. 23. Request & ActionResource GET PUT POST DELETE list collection replace create delete list data replace/ create ? / create delete
  24. 24. Mobile App with Web Services http request Data Req Provider (2) (1) Data Parse Res Data response * This is your destiny you cannot change your future, accept using vendor sdks
  25. 25. Call Web Services GET /user/anoochit REST Android Server 200 OK with XML or JSON string● HTTP request ● Check request method● Method GET, POST, PUT or DELETE ● Parse data from URI● Get BufferReader and pack into ● Process "String" <= JSON String ● Return XML or JSON string● Parse "String Key"● Get your value
  26. 26. No "official" standardThere is no "official" standard for RESTful webservices, This is because REST is anarchitectural style, unlike SOAP, which is aprotocol. Even though REST is not a standard,a RESTful implementation such as the Webcan use standards like HTTP, URI, XML, etc.
  27. 27. RESTful API DesignBut you should follow design guideline● RESTful API Design● Learn REST
  28. 28. Useful toolsif you want to test your RESTful web service bysent another method, try this● Advanced REST Client for Chrome● JSONView and JSONLint for Chrome● REST Client for Firefox
  29. 29. JSON Example{ "firstname": "Anuchit", "lastname": "Chalothorn"}
  30. 30. JSON Example[ { "firstname" : "Anuchit", "lastname" : "Chalothorn" }, { "firstname" : "Sira", "lastname" : "Nokyongthong" }]
  31. 31. Android & JSONJSON is a very condense data exchangeformat. Android includes the librarieswhich allow to work easily with JSON files.
  32. 32. JSON Object ParsingJSONObject c = new JSONObject(json);String firstname=c.get("firstname").toString();String lastname=c.get("lastname").toString();
  33. 33. JSON Array ParsingJSONArray data = new JSONArray(json);for (int i = 0; i < data.length(); i++) {JSONObject c = data.getJSONObject(i);String firstname = c.getString("firstname");String lastname = c.getString("lastname");}
  34. 34. Simple RESTful with PHPYou can make a simple RESTful API with PHPfor routing, process and response JSON data.The following tools you should have;● Web Server with PHP support● PHP Editor● REST Client plugin for browser
  35. 35. Workshop: JSON with PHPPHP has a function json_encode to generateJSON data from mix value. Create an App toread JSON data in a web server.header(Content-Type: application/json;charset=utf-8);$data = array("msg"=>"Hello World JSON");echo json_encode($data);
  36. 36. Workshop: JSON with PHPCreate multi-dimensional array the pass to jsonfunction to make a JSON Array data$data=array( array("firstname"=>"Anuchit", "lastname"=>"Chalothorn"), array("firstname"=>"Sira", "lastname"=>"Nokyongthong"));
  37. 37. Workshop: Check request methodsPHP has $_SERVER variable to check HTTPrequest methods of each request from client, soyou can check request from this variable.$method = $_SERVER["REQUEST_METHOD"];switch($method){ case "GET": break; ...}
  38. 38. RESTful DesignNow we can check request from client, now wecan follow the RESTful design guideline. Youmay use htaccess to make a beautiful URL. http://hostname/v1/contact/data service version number resource data
  39. 39. Call RESTful API GET /user/anoochit REST Android Server 200 OK with XML or JSON string● HTTP request ● Check request method● Method GET, POST, PUT or DELETE ● Parse data from URI● Get BufferReader and pack into ● Process "String" <= JSON String ● Return XML or JSON string● Parse "String Key"● Get your value
  40. 40. Workshop: Simple RESTfulMake RESTful service of this● Echo your name ○ sent your name with POST method and response with JSON result● Asking for date and time ○ sent GET method response with JSON result● Temperature unit converter ○ sent a degree number and type of unit with POST method and response JSON result
  41. 41. Workshop: RESTful Echo$data = array("result"=> "Hello, ".$_POST["name"]);echo json_encode($data);
  42. 42. Workshop: RESTful Date Time$data = array("result"=> date("d M Y H:i:s"));echo json_encode($data);
  43. 43. Workshop: RESTful Temperatureif ($_POST["type"]=="c") { $result=(($_POST["degree"]-32)*5)/9;} else { $result=(($_POST["degree"]*9)/5)+32;}$data = array("result"=>$result));echo json_encode($data);
  44. 44. Workshop: App REST EchoMake a mobile app call REST Echo API usingHttp Post method to send value.
  45. 45. Workshop: App REST TemperatureMake a mobile app call REST temperature unitconverter API, using Http Post method to senda degree value and unit type to convert.
  46. 46. Workshop: App REST Date TimeMake a mobile app call REST date time, usingHttp Get method to get a value of date andtime.
  47. 47. End