连接到网络
这一节将告诉你如何实现一个连接到网络的简单的应用程序。它说明了一些最佳的实践,即使是在创建最简单的联网app时也应该遵守的。
注意,要执行本节所描述的网络操作,你的应用的manifest必须包含如下的permissions:
1<uses-permission android:name="android.permission.INTERNET" /> 2<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
选择一个HTTP客户端
大多数的联网类android应用使用了HTTP来发送和接收数据。Android包含两种HTTP客户端: HttpURLConnection 和 Apache HttpClient 。它们两者都支持HTTPS,streamings上传和下载,可配置的超时,IPv6,和连接池。对于那些目标平台为Gingerbread或更高版本的应用,我们建议使用HttpURLConnection。关于这个主题的更多的讨论,请参考blog post Android's HTTP Clients 。
检查网络连接
在你的app尝试连接到网络之前,它应该先使用getActiveNetworkInfo()和isConnected()来检查一下,看看是否有一个可用的网络连接。记住,设备可能不在一个网络的范围内,或者用户可能已经禁用了Wi-Fi和移动数据访问。关于这个主题的更多讨论,请参考Managing Network Usage一节。
1public void myClickHandler(View view) { 2 ... 3 ConnectivityManager connMgr = (ConnectivityManager) 4 getSystemService(Context.CONNECTIVITY_SERVICE); 5 NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 6 if (networkInfo != null && networkInfo.isConnected()) { 7 // fetch data 8 } else { 9 // display error 10 } 11 ... 12}
在另一个线程中执行网络操作
网络操作可能会有一些不可预知的延时。为了防止由此而出现的糟糕的用户体验,则应该总是在UI线程之外的线程中来执行网络操作。AsyncTask类提供了一个最简单的方法,来在UI线程之外的一个线程中执行一个新的task。关于这个主题的更多讨论,请参考blog post Multithreading For Performance。
在下面的代码片段中,myClickHandler()方法调用了新的DownloadWebpageTask().execute(stringUrl)。DownloadWebpageTask类是AsyncTask的一个子类。DownloadWebpageTask实现了AsyncTask如下的方法:
-
doInBackground()执行downloadUrl()方法。它传递web page URL作为一个参数。downloadUrl()方法获取并处理web page的内容。当它结束时,它传回一个结果字符串。
-
onPostExecute()获取到返回的字符串并把它显示在UI中。
public class HttpExampleActivity extends Activity { private static final String DEBUG_TAG = "HttpExample"; private EditText urlText; private TextView textView;
1@Override 2public void onCreate(Bundle savedInstanceState) { 3 super.onCreate(savedInstanceState); 4 setContentView(R.layout.main); 5 urlText = (EditText) findViewById(R.id.myUrl); 6 textView = (TextView) findViewById(R.id.myText); 7} 8 9// When user clicks button, calls AsyncTask. 10// Before attempting to fetch the URL, makes sure that there is a network connection. 11public void myClickHandler(View view) { 12 // Gets the URL from the UI's text field. 13 String stringUrl = urlText.getText().toString(); 14 ConnectivityManager connMgr = (ConnectivityManager) 15 getSystemService(Context.CONNECTIVITY_SERVICE); 16 NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 17 if (networkInfo != null && networkInfo.isConnected()) { 18 new DownloadWebpageTask().execute(stringUrl); 19 } else { 20 textView.setText("No network connection available."); 21 } 22} 23 24 // Uses AsyncTask to create a task away from the main UI thread. This task takes a 25 // URL string and uses it to create an HttpUrlConnection. Once the connection 26 // has been established, the AsyncTask downloads the contents of the webpage as 27 // an InputStream. Finally, the InputStream is converted into a string, which is 28 // displayed in the UI by the AsyncTask's onPostExecute method. 29 private class DownloadWebpageTask extends AsyncTask<String, Void, String> { 30 @Override 31 protected String doInBackground(String... urls) { 32 33 // params comes from the execute() call: params[0] is the url. 34 try { 35 return downloadUrl(urls[0]); 36 } catch (IOException e) { 37 return "Unable to retrieve web page. URL may be invalid."; 38 } 39 } 40 // onPostExecute displays the results of the AsyncTask. 41 @Override 42 protected void onPostExecute(String result) { 43 textView.setText(result); 44 } 45} 46...}
这个代码片段的事件序列如下:
- 当用户按下button时,会调用myClickHandler(),app传递一个特定的URL给AsyncTask的子类DownloadWebpageTask。
- AsyncTask方法doInBackground()调用方法downloadUrl()。
- downloadUrl()方法获取到一个URL字符串作为参数,然后使用它来创建一个URL对象。
- URL对象被用来建立一个HttpURLConnection。
- 一旦建立了连接,则HttpURLConnection对象以一个InputStream的形式来获取web page的内容。
- InputStream被传递给方法readIt(),它会把stream转换为一个字串。
- 最后,AsyncTask的onPostExecute()方法在main activity的UI中显示字符串。
连接并下载数据
在你的执行网络事物的线程中,你可以使用HttpURLConnection来执行一个GET并下载你的数据。在你调用了connect()之后,你可以通过调用getInputStream()来获取一个数据的InputStream。
在下面的代码片段中,doInBackground()方法调用了downloadUrl()方法。downloadUrl()方法拿到给定的URL,并使用它来通过HttpURLConnection连接到网络。一旦建立了一个连接,则app使用getInputStream()来以一个InputStream提取数据。
1// Given a URL, establishes an HttpUrlConnection and retrieves 2// the web page content as a InputStream, which it returns as 3// a string. 4private String downloadUrl(String myurl) throws IOException { 5 InputStream is = null; 6 // Only display the first 500 characters of the retrieved 7 // web page content. 8 int len = 500; 9 10 try { 11 URL url = new URL(myurl); 12 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 13 conn.setReadTimeout(10000 /* milliseconds */); 14 conn.setConnectTimeout(15000 /* milliseconds */); 15 conn.setRequestMethod("GET"); 16 conn.setDoInput(true); 17 // Starts the query 18 conn.connect(); 19 int response = conn.getResponseCode(); 20 Log.d(DEBUG_TAG, "The response is: " + response); 21 is = conn.getInputStream(); 22 23 // Convert the InputStream into a string 24 String contentAsString = readIt(is, len); 25 return contentAsString; 26 27 // Makes sure that the InputStream is closed after the app is 28 // finished using it. 29 } finally { 30 if (is != null) { 31 is.close(); 32 } 33 } 34}
注意getResponseCode()方法返回连接的status code。这是获取关于连接的额外信息的一种有用的方法。一个值为200的status code表示success。
把InputStream转为一个String
一个InputStream是一个可读的bytes源。一旦你获取了一个InputStream,把它解码或转换为一个目标数据类型是很常见的。比如,如果你在下载图像数据,你可以像下面这样解码并显示它:
1InputStream is = null; 2... 3Bitmap bitmap = BitmapFactory.decodeStream(is); 4ImageView imageView = (ImageView) findViewById(R.id.image_view); 5imageView.setImageBitmap(bitmap);
在上面所示的例子中,InputStream表示一个web page的文本。下面显示了如何把InputStream转换为一个string,以使activity可以在UI中显示它:
1// Reads an InputStream and converts it to a String. 2public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { 3 Reader reader = null; 4 reader = new InputStreamReader(stream, "UTF-8"); 5 char[] buffer = new char[len]; 6 reader.read(buffer); 7 return new String(buffer); 8}
译自:http://developer.android.com/training/basics/network-ops/connecting.html
Done。