Luca Bedogni Dipartimento di Scienze dellInformazione Universit di - - PowerPoint PPT Presentation
Luca Bedogni Dipartimento di Scienze dellInformazione Universit di - - PowerPoint PPT Presentation
Programming with Android: Network Operations Luca Bedogni Dipartimento di Scienze dellInformazione Universit di Bologna Outline Network operations : WebView Network operations : WebView and WebSettings Network operations : HTTP Client
Luca Bedogni – Network programming with Android
2
Outline
Network operations: OKHttp Network operations: Download Manager Network operations: HTTP Client Network operations: WebView and WebSettings Network operations: WebView Network operations: TCP/UDP Sockets Network operations: Volley
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
3
Android: Network Operations
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Ø In order to perform network operations (also the one described earlier), specific permissions must be set on the AndroidManifest.xml. Ø Failure in setting the permissions will cause the system to throw a run-time exception …
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
4
Android: Network Operations
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { // fetch data } else { // display error }
Ø Before the application attempts to connect to the network, it should check to see whether a network connection is available using getActiveNetworkInfo() and isConnected() …
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
5
Android: WebView Usage
WebView à A View that displays web pages, including simple browsing methods (history, zoom in/out/ search, etc).
Implemented by the WebView class
public WebView(Context contex)
Main methods: Ø public void loadUrl(String url) à load the HTML page at url Ø public void loadData(String data, String mimeType, string encoding) à load the HTML page contained in data
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
6
Android: WebView Usage
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
7
Android: WebView Usage By default, the WebView UI does not include any navigation button …However, callbacks methods are defined:
Øpublic void goBack() Øpublic void goForward() Øpublic void reload() Øpublic void clearHistory()
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
8
Android: WebView Usage It is possible to modify the visualization options of a WebView through the WebSettings class.
public WebSettings getSettings()
Some options: Ø void setJavaScriptEnabled(boolean) Ø void setBuildInZoomControls(boolean) Ø void setDefaultFontSize(int)
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
9
Android: Download Manager DownloadManager à System service that handles long-run HTTP downloads.
DownloadManager dm=(DownloadManager) getSystemService getSystemService(DOWNLOAD_SERVICE);
Ø 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.
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
10
Android: Download Manager
Request request=new DownloadManager.Request(Uri.parse(address));
Ø The Request class is used to specify a download request to the Download Manager.
Ø long enqueue(DownloadManager.Request) Ø Cursor query(DownloadManager.Query) Ø ParcelFileDescriptor openDownloadedFile(long) Main methods of the DownloadManager
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
11
Android: HTTP Classes HTTP (HyperText Tranfer Protocol): Network protocol for exchange/transfer data (hypertext)
Request/Resonse Communication Model
Ø HEAD Ø GET Ø POST Ø PUT Ø DELETE Ø TRACE Ø CONNECT
MAIN COMMANDS
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
12
Android: HTTP Classes HTTP (HyperText 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?) Ø HTTPUrlConnection à 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 AsynchTask (not the UI thread!).
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
13
Android: HTTP (Abstract) Classes Ø HttpClient à Interface for an HTTP client Ø HttpRequest à Interface for an HTTP request Ø HttpResponse à Interface for an HTTP response Ø ResponseHandler<T> à Handler that creates an object <T> from an HTTP Response Ø HttpContext à Context of the HTTP Request (request+response+data)
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
14
Android: HTTP Classes Ø HttpClient à Interface for an HTTP client
(DefaultHttpClient à implementation of an HttpClient)
HttpClient client=new DefaultHttpClient();
Main method: The public method execute(…) performs an HTTP request, and allows to process an HTTP reply from the HTTP server.
abstract<T> T execute execute(HttpUriRequest request, ResponseHandler <T> responseHandler)
One of the signature of execute()
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
15
Android: HTTP Classes Ø HttpRequest à Interface for an HTTP request Two implementations: HttpGet à implements the GET HTTP method HttpPost à Implements the POST HTTP method
HttpGet request=new HttpGet HttpGet(String address); HttpGet request=new HttpGet HttpGet(URI address);
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
16
Android: HTTP Classes Ø ResponseHandler <T> à Interface for creating an object <T> from an HttpResponse,
- btained after having executed an HttpRequest.
public abstract T handleResponse (HttpResponse res)
Method to override
Generally, <T> is a String (HTML code) …
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
17
Android: HTTP Classes Ø HttpPost à Implements the POST HTTP method
List<NomeValuePair> par=new ArrayList<NomeValuePair>() par.add(new BasicNameValuePair(“name”,”Marco”); HttpEntity postEntity=new UrlEncodedFormEntity UrlEncodedFormEntity(par); request.setEntity setEntity(postEntity);
Encapsulating a parameter …
HttpPost request=new HttpPost HttpPost(String address); HttpPost request=new HttpPost HttpPost(URI address);
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
18
Android: HTTP Classes
Basic HTTPClient Request-Response Application … HttpClient client=new DefaultHttpClient(); new DefaultHttpClient(); HttpGet request=new HttpGet(); new HttpGet(); request.setURI(“http//www.cs.unibo.it”); try { try { client.execute(request, responseHandler); client.execute(request, responseHandler); } catch (ClientProtocolException e) { catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { catch (IOException e) { e.printStackTrace(); }
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
19
Android: HTTP Classes
Basic HTTPClient Request-Response Application …
class MyResponseHandler implements ResponseHandler<String> { @Override public String handleResponse(HttpResponse response) { InputStream content=response.getEntity().getContent(); byte[] buffer=new byte[1024]; int numRead=0; ByteArrayOutputStream stream=new ByteArrayOutputStream(); while ((numRead=content.read(buffer))!=-1) stream.write(buffer, 0, numRead); content.close(); String result=new String(stream.toByteArray()); return result; } }
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
20
Android: HTTP Classes
HTTPUrlConnection à HTTP component to send and receive streaming data over the web.
- 1. Obtain a new HttpURLConnection by calling the URL.openConnection()
URL url = new URL("http://www.android.com/"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
- 2. Prepare the request, set the options (e.g. session cookies)
- 3. For POST commands, invoke setDoOutput(true). Transmit data by
writing to the stream returned by getOutputStream().
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012
21
Android: HTTP Classes
HTTPUrlConnection à 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 getInputStream(). InputStream in = new BufferedInputStream(urlConnection.getInputStream());
- 5. Close the session when ending reading the stream through disconnect().
urlConnection.disconnect();
Luca Bedogni – Network programming with Android
OKHttp vHTTP Client for Java applications vSupports multiplexing of different connections on a same socket vLower latency vCan compress larger downloads transparently vRepeated requests may be served through cache
22
Luca Bedogni – Network programming with Android
OKHttp builder vRequests are built through the builder paradigm
23
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("http://academic.lucabedogni.it") .build(); Request request = new Request.Builder() .header("Authorization", ”your authorization here") .url("http://academic.lucabedogni.it") .build();
Luca Bedogni – Network programming with Android
OKHttp: network calls vSynchronous call vAsynchronous call
24
Response response = client.newCall(request).execute(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) {} @Override public void onResponse(Call call, final Response response) { if (response.isSuccessful()) { // Here we have the response }
Luca Bedogni – Network programming with Android
Volley vVolley is an HTTP library vSupports scheduling of network requests vCan have concurrent connections and handles priorities vCaching mechanism
25
Luca Bedogni – Network programming with Android
Volley: sending a request
26
Luca Bedogni – Network programming with Android
Volley: sending a request
27
RequestQueue queue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.GET, baseUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { // do something } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // do something } }); queue.add(stringRequest);
Luca Bedogni – Network programming with Android
(c) Luca Bedogni 2012