1page.title=Connecting to the Network 2parent.title=Performing Network Operations 3parent.link=index.html 4 5trainingnavtop=true 6next.title=Managing Network Usage 7next.link=managing.html 8 9@jd:body 10 11<div id="tb-wrapper"> 12<div id="tb"> 13 14 15 16<h2>This lesson teaches you to</h2> 17<ol> 18 <li><a href="#http-client">Choose an HTTP Client</a></li> 19 <li><a href="#connection">Check the Network Connection</a></li> 20 <li><a href="#AsyncTask">Perform Network Operations on a Separate Thread</a></li> 21 <li><a href="#download">Connect and Download Data</a></li> 22 <li><a href="#stream">Convert the InputStream to a String</a></li> 23 24</ol> 25 26<h2>You should also read</h2> 27<ul> 28 <li><a href="{@docRoot}training/volley/index.html">Transmitting Network Data Using Volley</a></li> 29 <li><a href="{@docRoot}training/monitoring-device-state/index.html">Optimizing Battery Life</a></li> 30 <li><a href="{@docRoot}training/efficient-downloads/index.html">Transferring Data Without Draining the Battery</a></li> 31 <li><a href="{@docRoot}guide/webapps/index.html">Web Apps Overview</a></li> 32 <li><a href="{@docRoot}guide/components/fundamentals.html">Application Fundamentals</a></li> 33</ul> 34 35</div> 36</div> 37 38<p>This lesson shows you how to implement a simple application that connects to 39the network. It explains some of the best practices you should follow in 40creating even the simplest network-connected app.</p> 41 42<p>Note that to perform the network operations described in this lesson, your 43application manifest must include the following permissions:</p> 44 45<pre><uses-permission android:name="android.permission.INTERNET" /> 46<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /></pre> 47 48 49 50<h2 id="http-client">Choose an HTTP Client</h2> 51 52<p>Most network-connected Android apps use HTTP to send and receive data. The 53Android platform includes the {@link java.net.HttpURLConnection} client, which 54supports HTTPS, streaming uploads and downloads, configurable timeouts, 55IPv6, and connection pooling.</p> 56 57<h2 id="connection">Check the Network Connection</h2> 58 59<p>Before your app attempts to connect to the network, it should check to see whether a 60network connection is available using 61{@link android.net.ConnectivityManager#getActiveNetworkInfo getActiveNetworkInfo()} 62and {@link android.net.NetworkInfo#isConnected isConnected()}. 63Remember, the device may be out of range of a 64network, or the user may have disabled both Wi-Fi and mobile data access. 65For more discussion of this topic, see the lesson <a 66href="{@docRoot}training/basics/network-ops/managing.html">Managing Network 67Usage</a>.</p> 68 69<pre> 70public void myClickHandler(View view) { 71 ... 72 ConnectivityManager connMgr = (ConnectivityManager) 73 getSystemService(Context.CONNECTIVITY_SERVICE); 74 NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 75 if (networkInfo != null && networkInfo.isConnected()) { 76 // fetch data 77 } else { 78 // display error 79 } 80 ... 81}</pre> 82 83<h2 id="AsyncTask">Perform Network Operations on a Separate Thread</h2> 84 85<p>Network operations can involve unpredictable delays. To prevent this from 86causing a poor user experience, always perform network operations on a separate 87thread from the UI. The {@link android.os.AsyncTask} class provides one of the 88simplest ways to fire off a new task from the UI thread. For more discussion of 89this topic, see the blog post <a 90href="http://android-developers.blogspot.com/2010/07/multithreading-for- 91performance.html">Multithreading For Performance</a>.</p> 92 93 94<p>In the following snippet, the <code>myClickHandler()</code> method invokes <code>new 95DownloadWebpageTask().execute(stringUrl)</code>. The 96<code>DownloadWebpageTask</code> class is a subclass of {@link 97android.os.AsyncTask}. <code>DownloadWebpageTask</code> implements the following 98{@link android.os.AsyncTask} methods:</p> 99 100 <ul> 101 102 <li>{@link android.os.AsyncTask#doInBackground doInBackground()} executes 103the method <code>downloadUrl()</code>. It passes the web page URL as a 104parameter. The method <code>downloadUrl()</code> fetches and processes the web 105page content. When it finishes, it passes back a result string.</li> 106 107 <li>{@link android.os.AsyncTask#onPostExecute onPostExecute()} takes the 108returned string and displays it in the UI.</li> 109 110 111 </ul> 112 113<pre> 114public class HttpExampleActivity extends Activity { 115 private static final String DEBUG_TAG = "HttpExample"; 116 private EditText urlText; 117 private TextView textView; 118 119 @Override 120 public void onCreate(Bundle savedInstanceState) { 121 super.onCreate(savedInstanceState); 122 setContentView(R.layout.main); 123 urlText = (EditText) findViewById(R.id.myUrl); 124 textView = (TextView) findViewById(R.id.myText); 125 } 126 127 // When user clicks button, calls AsyncTask. 128 // Before attempting to fetch the URL, makes sure that there is a network connection. 129 public void myClickHandler(View view) { 130 // Gets the URL from the UI's text field. 131 String stringUrl = urlText.getText().toString(); 132 ConnectivityManager connMgr = (ConnectivityManager) 133 getSystemService(Context.CONNECTIVITY_SERVICE); 134 NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 135 if (networkInfo != null && networkInfo.isConnected()) { 136 new DownloadWebpageTask().execute(stringUrl); 137 } else { 138 textView.setText("No network connection available."); 139 } 140 } 141 142 // Uses AsyncTask to create a task away from the main UI thread. This task takes a 143 // URL string and uses it to create an HttpUrlConnection. Once the connection 144 // has been established, the AsyncTask downloads the contents of the webpage as 145 // an InputStream. Finally, the InputStream is converted into a string, which is 146 // displayed in the UI by the AsyncTask's onPostExecute method. 147 private class DownloadWebpageTask extends AsyncTask<String, Void, String> { 148 @Override 149 protected String doInBackground(String... urls) { 150 151 // params comes from the execute() call: params[0] is the url. 152 try { 153 return downloadUrl(urls[0]); 154 } catch (IOException e) { 155 return "Unable to retrieve web page. URL may be invalid."; 156 } 157 } 158 // onPostExecute displays the results of the AsyncTask. 159 @Override 160 protected void onPostExecute(String result) { 161 textView.setText(result); 162 } 163 } 164 ... 165}</pre> 166 167<p>The sequence of events in this snippet is as follows:</p> 168<ol> 169 170 <li>When users click the button that invokes {@code myClickHandler()}, 171 the app passes 172the specified URL to the {@link android.os.AsyncTask} subclass 173<code>DownloadWebpageTask</code>.</li> 174 175 <li>The {@link android.os.AsyncTask} method {@link 176android.os.AsyncTask#doInBackground doInBackground()} calls the 177<code>downloadUrl()</code> method. </li> 178 179 <li>The <code>downloadUrl()</code> method takes a URL string as a parameter 180and uses it to create a {@link java.net.URL} object.</li> 181 182 <li>The {@link java.net.URL} object is used to establish an {@link 183java.net.HttpURLConnection}.</li> 184 185 <li>Once the connection has been established, the {@link 186java.net.HttpURLConnection} object fetches the web page content as an {@link 187java.io.InputStream}.</li> 188 189 <li>The {@link java.io.InputStream} is passed to the <code>readIt()</code> 190method, which converts the stream to a string.</li> 191 192 <li>Finally, the {@link android.os.AsyncTask}'s {@link 193android.os.AsyncTask#onPostExecute onPostExecute()} method displays the string 194in the main activity's UI.</li> 195 196</ol> 197 198 <h2 id="download">Connect and Download Data</h2> 199 200 <p>In your thread that performs your network transactions, you can use 201 {@link java.net.HttpURLConnection} to perform a {@code GET} and download your data. 202 After you call {@code connect()}, you can get an {@link java.io.InputStream} of the data 203 by calling {@code getInputStream()}. 204 205 <p>In the following snippet, the {@link android.os.AsyncTask#doInBackground 206doInBackground()} method calls the method <code>downloadUrl()</code>. The 207<code>downloadUrl()</code> method takes the given URL and uses it to connect to 208the network via {@link java.net.HttpURLConnection}. Once a connection has been 209established, the app uses the method <code>getInputStream()</code> to retrieve 210the data as an {@link java.io.InputStream}.</p> 211 212<pre> 213// Given a URL, establishes an HttpUrlConnection and retrieves 214// the web page content as a InputStream, which it returns as 215// a string. 216private String downloadUrl(String myurl) throws IOException { 217 InputStream is = null; 218 // Only display the first 500 characters of the retrieved 219 // web page content. 220 int len = 500; 221 222 try { 223 URL url = new URL(myurl); 224 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 225 conn.setReadTimeout(10000 /* milliseconds */); 226 conn.setConnectTimeout(15000 /* milliseconds */); 227 conn.setRequestMethod("GET"); 228 conn.setDoInput(true); 229 // Starts the query 230 conn.connect(); 231 int response = conn.getResponseCode(); 232 Log.d(DEBUG_TAG, "The response is: " + response); 233 is = conn.getInputStream(); 234 235 // Convert the InputStream into a string 236 String contentAsString = readIt(is, len); 237 return contentAsString; 238 239 // Makes sure that the InputStream is closed after the app is 240 // finished using it. 241 } finally { 242 if (is != null) { 243 is.close(); 244 } 245 } 246}</pre> 247 248<p>Note that the method <code>getResponseCode()</code> returns the connection's 249<a href="http://www.w3.org/Protocols/HTTP/HTRESP.html">status code</a>. This is 250a useful way of getting additional information about the connection. A status 251code of 200 indicates success.</p> 252 253<h2 id="stream">Convert the InputStream to a String</h2> 254 255<p>An {@link java.io.InputStream} is a readable source of bytes. Once you get an {@link java.io.InputStream}, 256it's common to decode or convert it into a 257target data type. For example, if you were downloading image data, you might 258decode and display it like this:</p> 259 260<pre>InputStream is = null; 261... 262Bitmap bitmap = BitmapFactory.decodeStream(is); 263ImageView imageView = (ImageView) findViewById(R.id.image_view); 264imageView.setImageBitmap(bitmap); 265</pre> 266 267<p>In the example shown above, the {@link java.io.InputStream} represents the text of a 268web page. This is how the example converts the {@link java.io.InputStream} to 269a string so that the activity can display it in the UI:</p> 270 271<pre>// Reads an InputStream and converts it to a String. 272public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { 273 Reader reader = null; 274 reader = new InputStreamReader(stream, "UTF-8"); 275 char[] buffer = new char[len]; 276 reader.read(buffer); 277 return new String(buffer); 278}</pre> 279 280 281 282