RungHung Gau - PowerPoint PPT Presentation

1 / 39
About This Presentation
Title:

RungHung Gau

Description:

bufResult.append(' tr th width='50%' Time /th ' ' th Temperature /th ... bufResult.append(' /table /body /html '); return(bufResult.toString()); Reference ... – PowerPoint PPT presentation

Number of Views:56
Avg rating:3.0/5.0
Slides: 40
Provided by: Mica3
Category:
Tags: runghung | append | gau

less

Transcript and Presenter's Notes

Title: RungHung Gau


1
Networking
  • Rung-Hung Gau
  • Department of Computer Science and Engineering
  • National Sun Yat-Sen University
  • Kaohsiung, Taiwan

2
Outline
  • Web Browser in Android
  • Networking in Android
  • HTTP Operations via Apache HttpComponents
  • Parsing Responses (DOM)

3
Web Browser in Android
  • WebView (Browser in Android)
  • loadUrl()
  • loadData() and loadDataWithBaseURL()
  • The WebViewClient Interface and
    WebView.setWebViewClient()
  • shouldOverrideUrlLoading(WebView view, String url)

4
Webkit-based Browser
  • You can embed the built-in Web browser as a
    widget in your own activities for displaying HTML
    or full-fledged browsing.
  • The Android browser is based on WebKit, the same
    engine that powers Apple's Safari Web browser.
  • The Android browser gets its own Java package
    (android.webkit)
  • Here is an example that shows up a webpage

5
(No Transcript)
6
  • lt?xml version"1.0" encoding"utf-8"?gt
  • ltLinearLayout xmlnsandroid"http//schemas.androi
    d.com/apk/res/android"
  • androidorientation"vertical"
  • androidlayout_width"fill_parent"
  • androidlayout_height"fill_parent"
  • gt
  • ltWebView androidid"_at_id/webkit
  • androidlayout_height"fill_parent"
  • /gt
  • lt/LinearLayoutgt

7
  • package com.commonsware.android.webkit
  • import android.app.Activity
  • import android.os.Bundle
  • import android.webkit.WebView
  • public class BrowserDemo1 extends Activity
  • WebView browser
  • _at_Override
  • public void onCreate(Bundle icicle)
  • super.onCreate(icicle)
  • setContentView(R.layout.main)

8
  • / get the WebView widget from the
    LinearLayout /
  • browser(WebView)findViewById(R.id.webkit)
  • / use the WebView widget to display a webpage
    /
  • browser.loadUrl("http//commonsware.com")

9
  • ltmanifest xmlnsandroid"http//schemas.android.co
    m/apk/res/android"
  • package"com.commonsware.android.webkit"gt
  • ltuses-permission androidname"android.permissio
    n.INTERNET" /gt
  • ltapplicationgt
  • ltactivity androidname".BrowserDemo1"
    androidlabel"BrowserDemo1"gt
  • ltintent-filtergt
  • ltaction androidname"android.intent.actio
    n.MAIN" /gt
  • ltcategory androidname"android.intent.cat
    egory.LAUNCHER" /gt
  • lt/intent-filtergt
  • lt/activitygt
  • lt/applicationgt
  • lt/manifestgt

10
Webkit-based Browser
  • By default Javascript is turned off in WebView
    widgets.
  • If you want to enable Javascript, call
    getSettings().setJavaScriptEnabled(true) on the
    WebView instance.

11
Webkit-based Browser
  • Besides loadUrl, you can use loadData() to supply
    the HTML for the browser to view.
  • There are two flavors of loadData().
  • The simpler one allows you to provide the
    content, the MIME type, and the encoding, all as
    strings.
  • browser.loadData("lthtmlgtltbodygtHello,
    world!lt/bodygtlt/htmlgt", "text/html", "UTF-8")

12
(No Transcript)
13
Webkit-based Browser
  • WebView offers ways to perform browser
    navigation, including
  • reload() to refresh the currently-viewed Web page
  • goBack() to go back one step in the browser
    history, and canGoBack() to determine if there is
    any history to go back to
  • goForward() to go forward one step in the browser
    history, and canGoForward() to determine if there
    is any history to go forward to

14
Webkit-based Browser
  • goBackOrForward() to go backwards or forwards in
    the browser history, where negative numbers
    represent a count of steps to go backwards, and
    positive numbers represent how many steps to go
    forwards
  • canGoBackOrForward() to see if the browser can go
    backwards or forwards the stated number of steps
  • clearCache() to clear the browser resource cache
    and clearHistory() to clear the browsing history

15
Webkit-based Browser
  • Your hook into the WebView activity is via
    setWebViewClient(), which takes an instance of a
    WebViewClient implementation as a parameter.
  • The supplied callback object will be notified of
    a wide range of activities such as
  • onPageStarted()
  • onTooManyRedirects()
  • onReceivedHttpAuthRequest()
  • Here is a browser-based equivalent of our
    original example an application that, upon a
    click, shows the current time.

16
(No Transcript)
17
  • public class BrowserDemo3 extends Activity
  • WebView browser
  • _at_Override
  • public void onCreate(Bundle icicle)
  • super.onCreate(icicle)
  • setContentView(R.layout.main)
  • browser(WebView)findViewById(R.id.webkit)
  • / set the callback object that deals with
    browser events /
  • browser.setWebViewClient(new Callback())
  • loadTime()

18
  • void loadTime()
  • String page"lthtmlgtltbodygtlta href\"clock\"gt
    new Date().toString() "lt/agtlt/bodygtlt/htmlgt"
  • browser.loadDataWithBaseURL("x-data//base",
    page, "text/html", "UTF-8", null)
  • private class Callback extends WebViewClient
  • public boolean shouldOverrideUrlLoading(WebVie
    w view, String url)

19
  • / your callback is passed a URL (plus the
    WebView itself) and you return true if you will
    handle the request or false if you want default
    handling (e.g., actually fetch the Web page
    referenced by the URL). /
  • / for some URLs you can override, while for
    some other URLs, you can use the default
    handling. /
  • / The differentiation could depends on the URL
    and the WebView instance /
  • loadTime()
  • return(true)

20
WebSettings
  • Control the font sizing via setDefaultFontSize()
    (to use a point size) or setTextSize() (to use
    constants indicating relative sizes like LARGER
    and SMALLEST)
  • Control Javascript via setJavaScriptEnabled() (to
    disable it outright) and setJavaScriptCanOpenWindo
    wsAutomatically() (to merely stop it from opening
    pop-up windows)
  • The settings you change are not persistent!!

21
WebSettings
  • Control Web site rendering via setUserAgent()
  • 0 means the WebView gives the Web site a
    user-agent string that indicates it is a mobile
    browser,
  • 1 results in a user-agent string that suggests it
    is a desktop browser

22
Internet Access in Android
  • The expectation is that most, if not all, Android
    devices will have built-in Internet access.
  • Networking APIs
  • raw sockets
  • WebView
  • HTTP, SMTP and so on (both on-device and from
    3rd-party JARs)

23
Internet Access in Android
  • Android does not have built-in SOAP or XML-RPC
    client APIs.
  • However, it does have the Apache HttpComponents
    library baked in.
  • REST-style Web services is defined as simple
    HTTP requests for ordinary URLs over the full
    range of HTTP verbs, with formatted payloads
    (XML, JSON, etc.) as responses".

24
HTTP Operations via Apache HttpComponents
  • The first step to using HttpClient is to create
    an HttpClient object.
  • The client object handles all HTTP requests on
    your behalf.
  • Since HttpClient is an interface, you will need
    to actually instantiate some implementation of
    that interface, such as DefaultHttpClient.

25
HTTP Operations via Apache HttpComponents
  • First, you create an HttpRequest implementation
    instance, with different HttpRequest
    implementations for each different HTTP verb.
  • HttpGet for HTTP GET requests
  • HttpPost for HTTP POST requests
  • Second, you fill in the URL to retrieve and other
    configuration data (e.g., form values for
    HttpPost)
  • Last, you pass the method to the HttpClient
    instance to actually make the HTTP request via
    HttpClient.execute().

26
HTTP Operations via Apache HttpComponents
  • You can get an HttpResponse object back by
  • public abstract HttpResponse execute (HttpHost
    target, HttpRequest request)
  • Or, you can get the response object generated by
    the response handler by
  • public abstract T execute (HttpUriRequest
    request, ResponseHandlerlt? extends Tgt
    responseHandler)
  • There are a variety of execute methods in the
    HttpClient interface.

27
(No Transcript)
28
An Example of Web Service
  • The updateForcast() method is called in
    onResume().
  • The onResume() method is called just before your
    activity comes to the foreground.
  • The updateForecast() method takes a Location as a
    parameter, obtained from the location update
    process.
  • The getLatitude() and getLongitude() methods
    return the latitude and longitude of the device's
    position, respectively.
  • We hold the URL to the National Weather Service
    XML in a string resource, and pour in the
    latitude and longitude at runtime.

29
An Example of Web Service
  • The HttpClient object is created in onCreate().
  • Given the resulting XML from the REST service, we
    build the forecast HTML page (see below) and pour
    that into the WebKit widget.
  • If the HttpClient blows up with an exception, we
    provide that error as a Toast.

30
  • private void updateForecast(Location loc)
  • / format a URL based on the current location /
  • String urlString.format(format,
    loc.getLatitude(), loc.getLongitude())
  • / use the HTTP GET method for web service /
  • HttpGet getMethodnew HttpGet(url)
  • try
  • / The ResponseHandler will handle the HTTP
    response /
  • ResponseHandlerltStringgt responseHandler new
    BasicResponseHandler()
  • / There are many flavors of HttpClient.execute()
    methods. /
  • / You get the response object generated by the
    response handler. In this case, a String /
  • String responseBodyclient.execute(getMethod,
    responseHandler)

31
  • / build the forecasts collection based on the
    data retrieved from REST web service /
  • buildForecasts(responseBody)
  • / generate the HTML file/table to be display
    in Browser /
  • String pagegeneratePage()
  • / show the HTML file/table in the Browser /
  • browser.loadDataWithBaseURL(null, page,
    "text/html", "UTF-8", null)
  • catch (Throwable t)
  • Toast.makeText(this, "Request failed
    "t.toString(), 4000).show()

32
Parsing Responses
  • The response you get will be formatted using some
    system HTML, XML, JSON, and etc.
  • In the case of the WeatherDemo, we need to
    extract the forecast time, temperature, and icon
    (indicating sky conditions and precipitation) and
    generate an HTML page from it.
  • We have to parse the response data to extract
    useful information.

33
Parsing Responses
  • Android includes three XML parsers
  • the traditional W3C DOM (org.w3c.dom),
  • a SAX parser (org.xml.sax),
  • and the XML pull parser
  • Android also includes a JSON parser (org.json)
  • For WeatherDemo, we use the W3C DOM parser in our
    buildForecasts() method.

34
Parsing Responses
  • The HTML comes in as an InputStream and is fed
    into the DOM parser.
  • From there, we scan for the start-valid-time
    elements and populate a set of Forecast models
    using those start times.
  • Then, we find the temperature value elements and
    icon-link URLs and fill those in to the Forecast
    objects.
  • In turn, the generatePage() method creates a
    rudimentary HTML table based on the Forecast
    object.

35
  • void buildForecasts(String raw) throws Exception
  • DocumentBuilder builderDocumentBuilderFactory.n
    ewInstance().newDocumentBuilder()
  • / Use DOM to create a tagged tree from the raw
    string /
  • Document docbuilder.parse(new InputSource(new
    StringReader(raw)))
  • NodeList timesdoc.getElementsByTagName("start-v
    alid-time")
  • for (int i0ilttimes.getLength()i)
  • Element time(Element)times.item(i)
  • Forecast forecastnew Forecast()
  • forecasts.add(forecast)
  • forecast.setTime(time.getFirstChild().getNodeV
    alue())

36
  • NodeList tempsdoc.getElementsByTagName("value")
  • for (int i0ilttemps.getLength()i)
  • Element temp(Element)temps.item(i)
  • Forecast forecastforecasts.get(i)
  • forecast.setTemp(new Integer(temp.getFirstChil
    d().getNodeValue()))
  • NodeList iconsdoc.getElementsByTagName("icon-li
    nk")
  • for (int i0ilticons.getLength()i)
  • Element icon(Element)icons.item(i)
  • Forecast forecastforecasts.get(i)
  • forecast.setIcon(icon.getFirstChild().getNodeV
    alue())

37
  • String generatePage()
  • / The method creates a rudimentary HTML table
    based on the forecasts collection /
  • StringBuffer bufResultnew StringBuffer("lthtmlgtlt
    bodygtlttablegt")
  • bufResult.append("lttrgtltth width\"50\"gtTimelt/th
    gt" "ltthgtTemperaturelt/thgtltthgtForecastlt/thgtlt/trgt")
  • / forecasts is a collection /
  • for (Forecast forecast forecasts)
  • bufResult.append("lttrgtlttd align\"center\"gt")
  • bufResult.append(forecast.getTime())
  • bufResult.append("lt/tdgtlttd align\"center\"gt")
  • bufResult.append(forecast.getTemp())
  • bufResult.append("lt/tdgtlttdgtltimg src\"")

38
  • bufResult.append(forecast.getIcon())
  • bufResult.append("\"gtlt/tdgtlt/trgt")
  • bufResult.append("lt/tablegtlt/bodygtlt/htmlgt")
  • return(bufResult.toString())

39
Reference
  • http//developer.android.com/reference/packages.ht
    ml
Write a Comment
User Comments (0)
About PowerShow.com