how to implement a simple application that connects to the network. It explains some of the best practices you should follow in creating even the simplest network-connected app.
Note that to perform the network operations described in this lesson, your application manifest must include the following permissions:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Choose an HTTP Client
Most network-connected Android apps use HTTP to send and receive data. Android includes two HTTP clients: HttpURLConnection
and Apache HttpClient
. Both support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6, and connection pooling. We recommend using HttpURLConnection
for applications targeted at Gingerbread and higher. For more discussion of this topic, see the blog post Android's HTTP Clients.
Check the Network Connection
Before your app attempts to connect to the network, it should check to see whether a network connection is available using getActiveNetworkInfo()
and isConnected()
. Remember, the device may be out of range of a network, or the user may have disabled both Wi-Fi and mobile data access. For more discussion of this topic, see the lesson Managing Network Usage.
Perform Network Operations on a Separate Thread
Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask
class provides one of the simplest ways to fire off a new task from the UI thread. For more discussion of this topic, see the blog post Multithreading For Performance.
In the following snippet, the myClickHandler()
method invokes new DownloadWebpageTask().execute(stringUrl)
. The DownloadWebpageTask
class is a subclass of AsyncTask
. DownloadWebpageTask
implements the following AsyncTask
methods:
-
doInBackground()
executes the method downloadUrl()
. It passes the web page URL as a parameter. The method downloadUrl()
fetches and processes the web page content. When it finishes, it passes back a result string. -
onPostExecute()
takes the returned string and displays it in the UI.
The sequence of events in this snippet is as follows:
- When users click the button that invokes
myClickHandler()
, the app passes the specified URL to the AsyncTask
subclass DownloadWebpageTask
. - The
AsyncTask
method doInBackground()
calls the downloadUrl()
method. - The
downloadUrl()
method takes a URL string as a parameter and uses it to create a URL
object. - The
URL
object is used to establish an HttpURLConnection
. - Once the connection has been established, the
HttpURLConnection
object fetches the web page content as an InputStream
. - The
InputStream
is passed to the readIt()
method, which converts the stream to a string. - Finally, the
AsyncTask
's onPostExecute()
method displays the string in the main activity's UI.
Connect and Download Data
In your thread that performs your network transactions, you can use HttpURLConnection
to perform a GET
and download your data. After you call connect()
, you can get an InputStream
of the data by calling getInputStream()
.
In the following snippet, the doInBackground()
method calls the method downloadUrl()
. The downloadUrl()
method takes the given URL and uses it to connect to the network via HttpURLConnection
. Once a connection has been established, the app uses the method getInputStream()
to retrieve the data as an InputStream
.
Note that the method getResponseCode()
returns the connection's status code. This is a useful way of getting additional information about the connection. A status code of 200 indicates success.
Convert the InputStream to a String
An InputStream
is a readable source of bytes. Once you get an InputStream
, it's common to decode or convert it into a target data type. For example, if you were downloading image data, you might decode and display it like this: