android nework api
DESCRIPTION
TRANSCRIPT
650003 – Mobile Computing (MCA 5th Semester)
1Mr. Pritesh N. Patel ( ISTAR )
Introduction to Mobile Networking
Android provide powerful API to design network
based application like accessing Internet,
design social networking application, etc.
Android uses powerful technologies and
libraries like java.net.* and android.net.*.
Android SDK provide a number of tools and
classes to design network based application.
We must take care while designing application
as resources are limited.
2Mr. Pritesh N. Patel ( ISTAR )
Accessing Internet ( HTTP)
Most commonly used protocol to transfer data
over internet is HTTP.
We use HTTP to transfer data from and to the
server over internet.
To transfer data securely SSL (Secure Socket
Layer) may be used.
3Mr. Pritesh N. Patel ( ISTAR )
Reading Data from webimport java.io.InputStream;
import java.net.URL;
public class FetchData extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
URL text = new URL(“http://www.yahoo.com/index.html”);
InputStream isText = text.openStream();
byte[] bText = new byte[250];
int readSize = isText.read(bText);
Log.i(“Net”, “readSize = “ + readSize);
Log.i(“Net”, “bText = “+ new String(bText));
isText.close();
}
}4Mr. Pritesh N. Patel ( ISTAR )
Permission to access Internet
Add following code in AndroidManifest.xml file
<uses-permission
android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.
ACCESS_NETWORK_STATE” />
5Mr. Pritesh N. Patel ( ISTAR )
HttpURLConnection class
This class is used to fetch more information about
url compare to URL class in pervious example.
Extra information may includes the length of the
content, content type, and date-time information.
6Mr. Pritesh N. Patel ( ISTAR )
Exampleimport java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FetchData extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
URL text = new URL(“http://www.yahoo.com/index.html”);
HttpURLConnection http = (HttpURLConnection)text.openConnection();
Log.i(“Net”, “length = “ + http.getContentLength());
Log.i(“Net”, “respCode = “ + http.getResponseCode());
Log.i(“Net”, “contentType = “+ http.getContentType());
Log.i(“Net”, “content = “+http.getContent());
}
}7Mr. Pritesh N. Patel ( ISTAR )
Processing XML from the Network
Android uses XML in varieties of ways like Android
resource file, manifest file, animation, layout design,
etc.
Also large number of data transferred over network
are in XML form.
We use Web service and RSS feed are in XML form.
Android provide class to process XML file same as
other files from file system.
XML Pull Parser is fast and efficient choice to parse
XML for network application
8Mr. Pritesh N. Patel ( ISTAR )
XMLPullParser Interface and more…
XML Pull Parser is an interface that defines
parsing functionality .
Xml Pull Parser (XPP) provides a simple and fast
implementation of "pull parsing model" that allows
processing application to request parsing events
incrementally.
There are two key methods: next() and
nextToken().
While next() provides access to high level parsing
events, nextToken() allows access to lower level
tokens.
9Mr. Pritesh N. Patel ( ISTAR )
Cont… The current event state of the parser can be
determined by calling the getEventType() method.Initially, the parser is in the START_DOCUMENTstate.
The method next() advances the parser to the nextevent. The int value returned from next determinesthe current parser state and is identical to the valuereturned from following calls to getEventType ().
The following event types are seen by next()
START_TAG An XML start tag was read.
TEXT Text content was read; the text content can beretrieved using the getText() method. (when invalidating mode next() will not report ignorablewhitespace, use nextToken() instead)
END_TAG An end tag was read
END_DOCUMENT No more events are available10Mr. Pritesh N. Patel ( ISTAR )
Steps…
Following steps are required to use XPP:
1. create an instance of XmlPullParserFactory usingnewInstance() method
2. create an instance of XmlPullParser usingnewPullParser() method on instance ofXmlPullParserFactory
3. set options (if they are different than defaults)
4. set input by calling eitherXmlPullParser.setInput(Reader) orXmlPullParser.setInput(char[])
5. start parsing by calling XmlPullParser.next() - thismethod returns event type and parsing is finishedwhen it returns XmlPullParser.END_DOCUMENTevent type.
11Mr. Pritesh N. Patel ( ISTAR )
Sample Code
12Mr. Pritesh N. Patel ( ISTAR )
Network Address Space
Network Address Description
10.0.2.1 Router/gateway address
10.0.2.2Special alias to your host loopback interface
(i.e., 127.0.0.1 on your development machine)
10.0.2.3 First DNS server
10.0.2.4 / 10.0.2.5 /
10.0.2.6
Optional second, third and fourth DNS server (if
any)
10.0.2.15The emulated device's own network/ethernet
interface
127.0.0.1 The emulated device's own loopback interface
13Mr. Pritesh N. Patel ( ISTAR )
Processing Asynchronously
AsyncTask enables proper and easy use of
the UI thread. This class allows to perform
background operations and publish results on the
UI thread without having to manipulate threads
and/or handlers.
An asynchronous task is defined by a computation
that runs on a background thread and whose
result is published on the UI thread. An
asynchronous task is defined by 3 generic types,
called Params, Progress and Result, and 4
steps, called onPreExecute, doInBackground,
onProgressUpdate and onPostExecute.14Mr. Pritesh N. Patel ( ISTAR )
AsyncTask must be extended in our own class to
use it’s functionality.
The subclass will override at least one method
(doInBackground(Params...)), and most often will
override a second one (onPostExecute(Result).)
Example
15Mr. Pritesh N. Patel ( ISTAR )
Steps…When an asynchronous task is executed, the task goes through 4 steps:
1. onPreExecute(), invoked on the UI thread immediately after the task isexecuted. This step is normally used to setup the task, for instance byshowing a progress bar in the user interface.
2. doInBackground(Params...), invoked on the background threadimmediately after onPreExecute() finishes executing. This step is usedto perform background computation that can take a long time. Theparameters of the asynchronous task are passed to this step. Theresult of the computation must be returned by this step and will bepassed back to the last step. This step can also usepublishProgress(Progress...) to publish one or more units of progress.These values are published on the UI thread, in theonProgressUpdate(Progress...) step.
3. onProgressUpdate(Progress...), invoked on the UI thread after a call topublishProgress(Progress...). The timing of the execution is undefined.This method is used to display any form of progress in the userinterface while the background computation is still executing. Forinstance, it can be used to animate a progress bar or show logs in atext field.
4. onPostExecute(Result), invoked on the UI thread after the backgroundcomputation finishes. The result of the background computation ispassed to this step as a parameter.
16Mr. Pritesh N. Patel ( ISTAR )
In Short……..1. doInBackground: Code performing long running
operation goes in this method. When onClickmethod is executed on click of button, it callsexecute method which accepts parameters andautomatically calls doInBackground method with theparameters passed.
2. onPostExecute: This method is called afterdoInBackground method completes processing.Result from doInBackground is passed to thismethod.
3. onPreExecute: This method is called beforedoInBackground method is called.
4. onProgressUpdate: This method is invoked bycalling publishProgress anytime fromdoInBackground call this method.
17Mr. Pritesh N. Patel ( ISTAR )