Programming with Android Network Operations Luca Bedogni Marco
Programming with Android: Network Operations Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna
Outline Network operations: Web. View and Web. Settings Network operations: HTTP Client Network operations: HTTP Requests Network operations: HTTP Responses Network operations: Download Manager Network operations: TCP/UDP Sockets Luca Bedogni, Marco Di Felice – Network programming with Android 2
Android: Network Operations Ø In order to perform network operations (also the one described earlier), specific permissions must be set on the Android. Manifest. xml. <uses-permission android: name="android. permission. INTERNET" /> <uses-permission android: name="android. permission. ACCESS_NETWORK_STATE" /> Ø Failure in setting the permissions will cause the system to throw a run-time exception … Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 3
Android: Network Operations Ø Before the application attempts to connect to the network, it should check to see whether a network connection is available using get. Active. Network. Info() and is. Connected() … Connectivity. Manager conn. Mgr = (Connectivity. Manager) get. System. Service(Context. CONNECTIVITY_SERVICE); Network. Info network. Info = conn. Mgr. get. Active. Network. Info(); if (network. Info != null && network. Info. is. Connected()) { // fetch data } else { // display error } Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 4
Android: Web. View Usage Web. View A View that displays web pages, including simple browsing methods (history, zoom in/out/ search, etc). Implemented by the Web. View class public Web. View(Context contex) Main methods: Ø public void load. Url(String url) load the HTML page at url Ø public void load. Data(String data, String mime. Type, string encoding) load the HTML page contained in data Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 5
Android: Web. View Usage Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 6
Android: Web. View Usage By default, the Web. View UI does not include any navigation button …However, callbacks methods are defined: Ø public void go. Back() Ø public void go. Forward() Ø public void reload() Ø public void clear. History() Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 7
Android: Web. View Usage It is possible to modify the visualization options of a Web. View through the Web. Settings class. public Web. Settings get. Settings() Some options: Ø void set. Java. Script. Enabled(boolean) Ø void set. Build. In. Zoom. Controls(boolean) Ø void set. Default. Font. Size(int) Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 8
Android: Download Manager Download. Manager System service that handles long-run HTTP downloads. Ø The client can specify the file to be downloaded through an URI (path). Ø Download is conducted in background (with retries) Ø Broadcast Intent action is sent to notify when the download completes. Download. Manager dm=(Download. Manager) get. System. Service(DOWNLOAD_SERVICE); Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 9
Android: Download Manager Ø The Request class is used to specify a download request to the Download Manager. Request request=new Download. Manager. Request(Uri. parse(address)); Main methods of the Download. Manager Ø long enqueue(Download. Manager. Request) Ø Cursor query(Download. Manager. Query) Ø Parcel. File. Descriptor open. Downloaded. File(long) Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 10
Android: HTTP Classes HTTP (Hyper. Text Tranfer Protocol): Network protocol for exchange/transfer data (hypertext) Request/Resonse Communication Model MAIN COMMANDS Ø Ø Ø Ø HEAD GET POST PUT DELETE TRACE CONNECT Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 11
Android: HTTP Classes HTTP (Hyper. Text Tranfer Protocol): Network protocol for exchange/transfer data (hypertext) Two implementations of HTTP Clients for Android: Ø HTTPClient Complete extendable HTTP Client suitable for web browser (not supported anymore? ) Ø HTTPUrl. Connection Light-weight implementation, suitable for client-server networking applications (recommended by Google) In both cases, HTTP connections must be managed on a separate thread, e. g. using Asynch. Task (not the UI thread!). Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 12
Android: HTTP (Abstract) Classes Ø Http. Client Interface for an HTTP client Ø Http. Request Interface for an HTTP request Ø Http. Response Interface for an HTTP response Ø Response. Handler<T> Handler that creates an object <T> from an HTTP Response Ø Http. Context of the HTTP Request (request+response+data) Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 13
Android: HTTP Classes Ø Http. Client Interface for an HTTP client (Default. Http. Client implementation of an Http. Client) Http. Client client=new Default. Http. Client(); Main method: The public method execute(…) performs an HTTP request, and allows to process an HTTP reply from the HTTP server. One of the signature of execute() abstract<T> T execute(Http. Uri. Request request, Response. Handler <T> response. Handler) Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 14
Android: HTTP Classes Ø Http. Request Interface for an HTTP request Two implementations: Http. Get implements the GET HTTP method Http. Get request=new Http. Get(String address); Http. Get request=new Http. Get(URI address); Http. Post Implements the POST HTTP method Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 15
Android: HTTP Classes Ø Response. Handler <T> Interface for creating an object <T> from an Http. Response, obtained after having executed an Http. Request. Method to override public abstract T handle. Response (Http. Response res) Generally, <T> is a String (HTML code) … Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 16
Android: HTTP Classes Ø Http. Post Implements the POST HTTP method Http. Post request=new Http. Post(String address); Http. Post request=new Http. Post(URI address); Encapsulating a parameter … List<Nome. Value. Pair> par=new Array. List<Nome. Value. Pair>() par. add(new Basic. Name. Value. Pair(“name”, ”Marco”); Http. Entity post. Entity=new Url. Encoded. Form. Entity(par); request. set. Entity(post. Entity); Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 17
Android: HTTP Classes Basic HTTPClient Request-Response Application … Http. Client client=new Default. Http. Client(); Http. Get request=new Http. Get(); request. set. URI(“http//www. cs. unibo. it”); try { client. execute(request, response. Handler); } catch (Client. Protocol. Exception e) { e. print. Stack. Trace(); } catch (IOException e) { e. print. Stack. Trace(); } Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 18
Android: HTTP Classes Basic HTTPClient Request-Response Application … class My. Response. Handler implements Response. Handler<String> { @Override public String handle. Response(Http. Response response) { Input. Stream content=response. get. Entity(). get. Content(); byte[] buffer=new byte[1024]; int num. Read=0; Byte. Array. Output. Stream stream=new Byte. Array. Output. Stream(); while ((num. Read=content. read(buffer))!=-1) stream. write(buffer, 0, num. Read); content. close(); String result=new String(stream. to. Byte. Array()); return result; } } Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 19
Android: HTTP Classes HTTPUrl. Connection HTTP component to send and receive streaming data over the web. 1. Obtain a new Http. URLConnection by calling the URL. open. Connection() URL url = new URL("http: //www. android. com/"); Http. URLConnection url. Connection = (Http. URLConnection) url. open. Connection(); 2. Prepare the request, set the options (e. g. session cookies) 3. For POST commands, invoke set. Do. Output(true). Transmit data by writing to the stream returned by get. Output. Stream(). Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 20
Android: HTTP Classes HTTPUrl. Connection HTTP component to send and receive streaming data over the web. 4. Read the response (data+header). The response body may be read from the stream returned by get. Input. Stream(). Input. Stream in = new Buffered. Input. Stream(url. Connection. get. Input. Stream()); 5. Close the session when ending reading the stream through disconnect(). url. Connection. disconnect(); Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 21
Android: TCP/IP Communication TCP/UDP Communication Android applications can use java. net. Socket facilities. Ø Use socket-based programming like in Java … Class Datagram. Socket UDP Socket Classes Socket/Server. Socket TCP socket Read/Write on Sockets through Input. Stream/Output. Stream Luca Bedogni, Marco Di Felice – Luca Bedogni 2012 Network programming with(c) Android 22
- Slides: 22