標籤:
原文地址:http://android.xsoftlab.net/training/basics/network-ops/index.html
引言
這節課將會學習最基本的網路連接,監視網路連接狀況及網路控制等內容。除此之外還會附帶描述如何解析、使用XML資料。
這節課所包含的範例程式碼示範了最基本的網路操作過程。開發人員可以將這部分的代碼作為應用程式最基本的網路作業碼。
通過這節課的學習,將會學到最基本的網路下載及資料解析的相關知識。
Note: 可以查看課程Transmitting Network Data Using Volley學習Volley的相關知識。這個HTTP庫可以使網路操作更方便更快捷。Volley是一個開源架構庫,可以使應用的網路操作順序更加合理並善於管理,還會改善應用的相關效能。
串連到網路
這節課將會學習如何?一個含有網路連接的簡單程式。課程中所描述的步驟是網路連接的最佳實現過程。
如果應用要使用網路操作,那麼資訊清單檔中應該包含以下許可權:
<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
選擇HTTP用戶端
大多數的Android應用使用HTTP來發送、接收資料。Android中包含了兩個HTPP用戶端:HttpURLConnection及Apache的HTTP用戶端。兩者都支援HTTPS,上傳,下載,逾時時間配置,IPv6,串連池。我們推薦在Gingerbread及以上的版本中使用HttpURLConnection。有關這個話題的更多討論資訊,請參見部落格Android’s HTTP Clients.
檢查網路連接狀況
在嘗試串連到網路之前,應當通過getActiveNetworkInfo()方法及isConnected()方法檢查網路連接是否可用。要記得,裝置可能處於不在網路範圍的情況中,也可能使用者並沒有開啟WIFI或者移動資料。該話題的更多資訊請參見 Managing Network Usage.
public void myClickHandler(View view) { ... ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { // fetch data } else { // display error } ...}
在子線程中執行網路操作
網路操作所用的時間通常是不確定的。為了防止由於網路操作而引起的糟糕的使用者體驗,應該將這個過程放入獨立的線程中執行。AsyncTask類為這種實現提供了協助。更多該話題的討論請參見Multithreading For Performance。
在下面的程式碼片段中,myClickHandler()方法調用了new DownloadWebpageTask().execute(stringUrl)。類DownloadWebpageTask是AsyncTask的子類。DownloadWebpageTask實現了AsyncTask的以下方法:
- doInBackground()中執行了downloadUrl()方法。它將Web頁的URL地址作為參數傳給了該方法。downloadUrl()方法會獲得並處理Web頁面的內容。當處理結束時,這個方法會將處理後的結果返回。
- onPostExecute()獲得返回後的結果將其顯示在UI上。
public class HttpExampleActivity extends Activity { private static final String DEBUG_TAG = "HttpExample"; private EditText urlText; private TextView textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); urlText = (EditText) findViewById(R.id.myUrl); textView = (TextView) findViewById(R.id.myText); } // When user clicks button, calls AsyncTask. // Before attempting to fetch the URL, makes sure that there is a network connection. public void myClickHandler(View view) { // Gets the URL from the UI‘s text field. String stringUrl = urlText.getText().toString(); ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { new DownloadWebpageTask().execute(stringUrl); } else { textView.setText("No network connection available."); } } // Uses AsyncTask to create a task away from the main UI thread. This task takes a // URL string and uses it to create an HttpUrlConnection. Once the connection // has been established, the AsyncTask downloads the contents of the webpage as // an InputStream. Finally, the InputStream is converted into a string, which is // displayed in the UI by the AsyncTask‘s onPostExecute method. private class DownloadWebpageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { // params comes from the execute() call: params[0] is the url. try { return downloadUrl(urls[0]); } catch (IOException e) { return "Unable to retrieve web page. URL may be invalid."; } } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { textView.setText(result); } } ...}
上面的代碼執行了以下操作:
- 1.當使用者按下按鈕時會調用myClickHandler()方法,應用會將指定的URL地址傳遞給DownloadWebpageTask。
- 2.DownloadWebpageTask的doInBackground()方法調用了downloadUrl()方法。
- 3.downloadUrl()方法將獲得的URL字串作為參數建立了一個URL對象。
- 4.URL對象被用來與HttpURLConnection建立串連。
- 5.一旦串連建立,HttpURLConnection會將擷取到的Web頁面內容作為輸入資料流輸入。
- 6.readIt()方法將輸入資料流轉換為String對象。
- 7.最後onPostExecute()方法將String對象顯示在UI上。
串連與下載資料
在執行網路傳輸的線程中可以使用HttpURLConnection來執行GET請求並下載輸入。在調用了connect()方法之後,可以通過getInputStream()方法獲得輸入資料流形式的資料。
在doInBackground()方法中調用了downloadUrl()方法。downloadUrl()方法將URL作為參數通過HttpURLConnection與網路建立串連。一旦串連建立,應用通過getInputStream()方法來接收位元組流形式的資料。
// Given a URL, establishes an HttpUrlConnection and retrieves// the web page content as a InputStream, which it returns as// a string.private String downloadUrl(String myurl) throws IOException { InputStream is = null; // Only display the first 500 characters of the retrieved // web page content. int len = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); Log.d(DEBUG_TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); return contentAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (is != null) { is.close(); } }}
注意getResponseCode()方法返回的是串連的狀態代碼。該狀態代碼可以用來擷取串連的其它資訊。狀態代碼為200則表明串連成功。
將位元組流轉換為字串
InputStream所讀取的是位元組資料。一旦獲得InputStream對象,通常需要將其解碼或者轉化為其它類型的資料。比如,如果下載了一張圖片,則應該將位元組流轉碼為圖片:
InputStream is = null;...Bitmap bitmap = BitmapFactory.decodeStream(is);ImageView imageView = (ImageView) findViewById(R.id.image_view);imageView.setImageBitmap(bitmap);
在上的樣本中,InputStream代表了Web頁面的常值內容。下面的代碼展示了如何將位元組流轉換為字串:
// Reads an InputStream and converts it to a String.public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer);}
Android官方開發文檔Training系列課程中文版:網路操作之網路連接