0% found this document useful (0 votes)
84 views

UNIT-5: Using Internet Resources

The document discusses various ways to use internet resources in Android applications including downloading and parsing data from the web, using APIs like Google APIs, and processing remote XML feeds. It describes using the Download Manager to handle long-running downloads in the background. Best practices are provided for optimizing the user experience such as limiting data usage and ensuring robustness for network outages.

Uploaded by

nandini p
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views

UNIT-5: Using Internet Resources

The document discusses various ways to use internet resources in Android applications including downloading and parsing data from the web, using APIs like Google APIs, and processing remote XML feeds. It describes using the Download Manager to handle long-running downloads in the background. Best practices are provided for optimizing the user experience such as limiting data usage and ensuring robustness for network outages.

Uploaded by

nandini p
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT-5

Using Internet
Resources
Contents
• DOWNLOADING AND PARSING INTERNET
RESOURCES
• USING THE DOWNLOAD MANAGER
• USING INTERNET SERVICES
• CONNECTING TO GOOGLE APP ENGINE
• BEST PRACTICES FOR DOWNLOADING DATA
WITHOUT DRAINING THE BATTERY-SLE
 DOWNLOADING AND PARSING INTERNET
RESOURCES
• Explains about several ways to make use internet
resources to the maximum extent.
• One way is to make use of Webview which
includes WebKit based browser within an activity.
• Another way is to use client-side APIs like Google
APIs,which interact directly with server processes.
• Apart from them we can process remote XML
feeds to extract and process data using java based
XML parser such as SAX or XML Pull parser
Cont..
• Benefits of creating thick and thin client native applications rather rely entirely
on web based solutions:
1. BandWidth--Static resources such as images, layouts, and sounds can be
expensive on devices with bandwidth restraints. By creating a native
application, you can limit the bandwidth requirements to changed data only.
2. Caching--A native application can cache data and user actions to provide as
much functionality as possible without a live connection and synchronize with
the cloud when a connection is reestablished.
3. Reducing battery drain — Each time your application opens a connection to a
server, the wireless radio will be turned on (or kept on). A native application can
bundle its connections, minimizing the number of connections initiated. The
longer the period between network requests, the longer the wireless radio can
be left off.
4. Native features — Android devices are more than simple platforms for running
a browser. They include location-based services, Notifications, widgets, camera
hardware, background Services, and hardware sensors. By creating a native
application, you can combine the data available online with the hardware
features available on the device to provide a richer user experience.
Cont..
• Modern mobile devices offer a number of alternatives for accessing the
Internet. Broadly speaking, Android provides two connection techniques for
Internet connectivity. Each is offered transparently to the application layer.
1. Mobile Internet — GPRS, EDGE, 3G, 4G,,5G and LTE Internet access is
available through carriers that offer mobile data.
2. Wi-Fi — Wi-Fi receivers and mobile hotspots are becoming increasingly
common.

• If you use Internet resources in your application, remember that your users’
data connections are dependent on the communications technology available
to them. EDGE and GSM connections are notoriously low-bandwidth,
whereas a Wi-Fi connection may be unreliable in a mobile setting.

• Optimize the user experience by limiting the quantity of data transmitted and
ensure that your application is robust enough to handle network outages and
bandwidth limitations.
• Connecting to an Internet Resource
• Before you can access Internet resources, you need
to add an INTERNET uses-permission node to your
application manifest, as shown in the following XML
snippet:
• <uses-permission
android:name=”android.permission.INTERNET”/>
• Android includes several classes to help you handle
network communications. They are available in the
java.net.* and android.net.* packages.
• Parsing XML Using the XML Pull Parser
• XML stands for Extensible Mark-up Language.XML is a very popular format
and commonly used for sharing data on the internet. It explains how to
parse the XML file and extract necessary information from it.
• Android provides three types of XML parsers which are DOM,SAX and
XMLPullParser. Among all of them android recommend XMLPullParser
because it is efficient and easy to use. So we are going to use XMLPullParser
for parsing XML.
• DOM(Document Object Model) –Loads XML file in memory then converts
into objects then starts parsing.
• XMLPullParser- presents elements of our document in a sequential series of
events and tags.
- Event based where we can pull only a particular XML node we are
intended
• SAX(Simple API for XML)-same like PullParser but no way to parse only
particular nodes
• Parsing XML Using the XML Pull Parser
• The XML Pull Parser API is available from the following
libraries:
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
• 1st step is to identify the fields in the XML data in which
we are interested
• 2nd step is to create XMLPullParserFactory object and then
call its NewPullParser() method to create XMLPullParser.
• 3rd step involves specifying the file for XMLPullParser that
contains XML .
Parsing XML Using the XML Pull Parser
• 4th step-XML file consists elements or components such as
events,name,text,attributevalue
• XMLPullParser has separate functions for specifying these
elements or components.
• 1)getEventType() returns the type of event that happens for
example START_DOUMENT event and END_DOCUMENT
• 2)getName() returns the name of the tag for example if we
are interested in particular information we can use it as tag.
• 3)getText() returns the text for that particular element.
• 4)getattributeValue() returns us the value of that particular
element.
Creating an Earthquake Viewer
• In this we create a tool that uses a USGS
earthquake feed to display a list of recent
earthquakes
• The earthquake feed XML is parsed here by the
DOM parser.
• In this example you’ll create a list-based Activity
that connects to an earthquake feed and
displays the location, magnitude, and time of
the earthquakes it contains.
1. Start by creating an Earthquake project featuring an Earthquake Activity.
2. Create a new EarthquakeListFragment that extends ListFragment. This
Fragment displays your list of earthquakes.
public class EarthquakeListFragment extends ListFragment {}
3. Modify the main.xml layout resource to include the Fragment you created in
Step 2.
<fragment android:name=”com.paad.earthquake.EarthquakeListFragment”
android:id=”@+id/EarthquakeListFragment”
android:layout_width=”match_parent”
android:layout_height=”match_parent”/>
4. Create a new public Quake class. This class will be used to store the details
(date, details,location, magnitude, and link) of each earthquake. Override the
toString method to provide the string that will be used to represent each quake
in the List View.
5.In the EarthquakeListFragment, override the onActivityCreated
method to store an ArrayList of Quake objects, and bind that to the
underlying ListView using an ArrayAdapter:
public class EarthquakeListFragment extends ListFragment {
ArrayAdapter<Quake> aa;
ArrayList<Quake> earthquakes = new
ArrayList<Quake>();
6. Start processing the earthquake feed. For this example, the feed
used is the one-day USGS feed for earthquakes with a magnitude
greater than 2.5. Add the location of your feed as an external string
resource. This lets you potentially specify a different feed based on a
user’s location.
7. Before your application can access the Internet, it aneeds to be
granted permission for Internet access. Add the Internet uses-
permission to the manifest:
• <uses-permission android:name=”android.permission.INTERNET”/>
8. Returning to the Earthquake List Fragment, create a new
refreshEarthquakes method that connects to and parses the
earthquake feed. Extract each earthquake and parse the details to
obtain the date, magnitude, link, and location. As you finish parsing
each earthquake, pass it in to a new addNewQuake method. Note that
the addNewQuake method is executed within a Runnable posted from
a Handler object. This allows you to execute the refreshEarthquakes
method on a background thread before updating the UI within
addNewQuake.
9. Update the addNewQuake method so that it takes
each newly processed quake and adds it to the
earthquake Array List. It should also notify the Array
Adapter that the underlying data has changed.
10. Modify your onActivityCreated method to call
refreshEarthquakes on startup. Network operations
should always be performed in a background thread.
11. When you run your project, you should see a List
View that features the earthquakes from the last 24
hours with a magnitude greater than 2.5.
 USING THE DOWNLOAD MANAGER
• The download manager is a system service that handles long-running
HTTP downloads.
• Clients may request that a URI be downloaded to a particular
destination file.
• The download manager will conduct the download in the background,
taking care of HTTP interactions and retrying downloads after failures
or across connectivity changes and system reboots.
• To access the Download Manager, request the DOWNLOAD_SERVICE
using the getSystemService method, as follows:
String serviceString = Context.DOWNLOAD_SERVICE;
DownloadManager downloadManager;
downloadManager =
DownloadManager)getSystemService(serviceString);
• Downloading Files
• To request a download, create a new DownloadManager.Request,
specifying the URI of the file to download and passing it in to the
Download Manager’s enqueue method.
• After calling enqueue, the download begins as soon as connectivity is
available and the Download Manager is free.
• To receive a notification when the download is completed, register a
Receiver to receive an ACTION_DOWNLOAD_COMPLETE broadcast. It
will include an EXTRA_DOWNLOAD_ID extra that contains the
reference ID of the download that has completed.
• You can use Download Manager’s openDownloadedFile method to
receive a Parcel File Descriptor to your file, to query the Download
Manager to obtain its location, or to manipulate it directly if you’ve
specified a filename and location yourself.
• Customizing Download Manager
Notifications
• By default, ongoing Notifications will be displayed for each
download managed by the Download Manager. Each
Notification will show the current download progress and
the filename.
• The Download Manager enables you to customize the
Notification displayed for each download request, including
hiding it completely. The following snippet shows how to
use the setTitle and setDescription methods to customize
the text displayed in the file download Notification.
request.setTitle(“Earthquakes”);
request.setDescription(“Earthquake XML”);
Cont..
• The setNotificationVisibility method lets you control when, and if, a
Notification should be displayed for your request using one of the
following flags:
1. Request.VISIBILITY_VISIBLE — An ongoing Notification will be visible for
the duration that the download is in progress. It will be removed when the
download is complete. This is the default option.
2. Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED—Anongoing Notification
will be displayed during the download and will continue to be displayed
(until selected or dismissed) once the download has completed.
3. Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION—The
notification will be displayed only after the download is complete.
4. Request.VISIBILITY_HIDDEN — No Notification will be displayed for this
download. Inorder to set this flag, your application must have the
DOWNLOAD_WITHOUT_NOTIFICATION uses-permission specified in its
manifest.
• Specifying a Download Location
• By default, all Download Manager downloads are saved to the shared
download cache using system generated filenames. Each Request object can
specify a download location, though all downloads must be stored
somewhere on external storage and the calling application must have the
WRITE_EXTERNAL_STORAGE uses-permission in its manifest:
<uses-permission
android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>
• The following code snippet shows how to specify an arbitrary path on external
storage:
request.setDestinationUri(Uri.fromFile(f));
• The following snippet specifies storing a file in your application’s external
downloads folder:
request.setDestinationInExternalFilesDir(this,
Environment.DIRECTORY_DOWNLOADS, “Bugdroid.png”);
• The following snippet requests a file be stored in the public music folder:
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_MUSIC,
“Android_Rock.mp3”);
• Cancelling and Removing Downloads
• The Download Manager’s remove method lets you cancel a
pending download, abort a download in progress, or delete a
completed download.
• As shown in the following code snippet, the remove method
accepts download IDs as optional arguments, enabling you to
specify one or many downloads to cancel:
downloadManager.remove(REFERENCE_1,
REFERENCE_2, REFERENCE_3);
• It returns the number of downloads successfully canceled. If a
download is canceled, all associated files — both partial and
complete — are removed.
• Querying the Download Manager
• You can query the Download Manager to find the status,
progress, and details of your download requests by using the
query method that returns a Cursor of downloads.
• The query method takes a downloadManager.Query object as a
parameter. Use the setFilterById method on a Query object to
specify a sequence of download reference IDs, or use the
setFilterByStatus method to filter on a download status using
one of the downloadManager.STATUS_* constants to specify
running, paused, failed, or successful downloads.
• The Download Manager includes a number of COLUMN_* static
String constants that you can use to query the result Cursor.
• You can find details for each download, including the status, fies
size, bytes downloaded so far, title, description, URI, local
filename and URI, media type, and Media Provider download
URI.
USING INTERNET SERVICES
• Google Services APIs — In addition to the native Google applications, Google offers
web APIs for access to their Calendar, Docs, Blogger, and Picasa Web Albums platforms.
These APIs collectively make use of a form of XML for data communication.
• Yahoo! Pipes — Yahoo! Pipes offers a graphical web-based approach to XML feed
manipulation. Using pipes, you can filter, aggregate, analyze, and otherwise manipulate
XML feeds and output them in a variety of formats to be consumed by your
applications.
• Google App Engine — Using the Google App Engine, you can create cloud-hosted web
services that shift complex processing away from your mobile client. Doing so reduces
the load on your system resources but comes at the price of Internet-connection
dependency. Google also offers Cloud Storage and Prediction API services.
• Amazon Web Services — Amazon offers a range of cloud-based services, including a
rich API for accessing its media database of books, CDs, and DVDs. Amazon also offers a
distributed storage solution (S3) and Elastic Compute Cloud (EC2).
CONNECTING TO GOOGLE APP ENGINE
• To use the Google Play Store, users must be signed in to a Google
account on their phones; therefore, if your application connects to a
Google App Engine backend to store and retrieve data related to a
particular user, you can use the Account Manager to handle the
authentication.
• The Account Manager enables you to ask users for permission to retrieve
an authentication token, which, in turn, can be used to obtain a cookie
from your server that can then be used to make future authenticated
requests.
• To retrieve accounts and authentication tokens from the Account
Manager, your application requires the GET_ACCOUNTS uses-permission:
<uses-permission
android:name=”android.permission.GET_ACCOUNTS”/>
Cont…
• Making authenticated Google App Engine requests is a three-part
process:
• 1. Request an auth token.
• 2. Use the auth token to request an auth cookie.
• 3. Use the auth cookie to make authenticated requests.
• The Account Manager then checks to see if the user has approved your
request for an auth token. The result is returned to your application via
the Account Manager Callback you specified when making the request.
• If the returned bundle is inspected for an Intent stored against the
AccountManager.KEY_INTENT key. If this key’s value is null, the user has
approved your application’s request, and you can retrieve the auth token
from the bundle.
• If the key’s value is not null, you must start a new Activity using the
bundled Intent to request the user’s permission. The user will be
prompted to approve or deny your request. After control has been passed
back to your application, you should request the auth token again.
private static int ASK_PERMISSION = 1;
private class GetAuthTokenCB implements AccountManagerCallback<Bundle> {
public void run(AccountManagerFuture<Bundle> result) {
try {
Bundle bundle = result.getResult();
Intent launch = (Intent)bundle.get(AccountManager.KEY_INTENT);
if (launch != null)
www.it-ebooks.info
Best Practices for Downloading Data Without Draining the Battery x 219
startActivityForResult(launch, ASK_PERMISSION);
else {
// Extract the auth token and request an auth cookie.
}
}
Cont..
• The auth token is stored within the Bundle parameter
against the AccountManager.KEY_ AUTHTOKEN, as follows:
• Stringauth_token=
bundle.getString(AccountManager.KEY_AUTHTOKEN);
• You can use this token to request an auth cookie from
Google App Engine by configuring an httpClient and using
it to transmit an HttpGet request.
• If the request was successful, simply iterate over the
Cookies stored in the HTTP Client’s Cookie Store to
confirm the auth cookie has been set.
• The HTTP Client used to make the request has the
authenticated cookie, and all future requests to Google
App Engine using it will be properly authenticated.

You might also like