Connecting to an Internet Resource

While the details of working with specific web services won't be covered within this book, it's useful to know the general principles of connecting to the Internet, and getting an input stream from a remote data source.

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"/>

Listing 5-26 shows the basic pattern for opening an Internet data stream.

STING 5-26: Opening a data stream

String myFeed = getString(R.string.my_feed); try {

URLConnection connection = url.openConnection();

HttpURLConnection httpConnection = (HttpURLConnection)connection;

int responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = httpConnection.getInputStream(); [ ... Process the input stream as required ... ]

catch (MalformedURLException e) { } catch (IOException e) { }

Android includes several classes to help you handle network communications. They are available in the* and* packages.

Later in this chapter is a fully worked example that shows how to obtain and process an Internet feed to get a list of earthquakes felt in the last 24 hours.

Chapter 13 features more information on managing specific Internet connections, including information on monitoring connection status and configuring Wi-Fi access point connections.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide

Post a comment