日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android官方开发文档Training系列课程中文版:网络操作之网络连接

發(fā)布時間:2024/7/5 Android 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android官方开发文档Training系列课程中文版:网络操作之网络连接 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

原文地址:http://android.xsoftlab.net/training/basics/network-ops/index.html

引言

這節(jié)課將會學(xué)習(xí)最基本的網(wǎng)絡(luò)連接,監(jiān)視網(wǎng)絡(luò)連接狀況及網(wǎng)絡(luò)控制等內(nèi)容。除此之外還會附帶描述如何解析、使用XML數(shù)據(jù)。

這節(jié)課所包含的示例代碼演示了最基本的網(wǎng)絡(luò)操作過程。開發(fā)者可以將這部分的代碼作為應(yīng)用程序最基本的網(wǎng)絡(luò)操作代碼。

通過這節(jié)課的學(xué)習(xí),將會學(xué)到最基本的網(wǎng)絡(luò)下載及數(shù)據(jù)解析的相關(guān)知識。

Note: 可以查看課程Transmitting Network Data Using Volley學(xué)習(xí)Volley的相關(guān)知識。這個HTTP庫可以使網(wǎng)絡(luò)操作更方便更快捷。Volley是一個開源框架庫,可以使應(yīng)用的網(wǎng)絡(luò)操作順序更加合理并善于管理,還會改善應(yīng)用的相關(guān)性能。

連接到網(wǎng)絡(luò)

這節(jié)課將會學(xué)習(xí)如何實現(xiàn)一個含有網(wǎng)絡(luò)連接的簡單程序。課程中所描述的步驟是網(wǎng)絡(luò)連接的最佳實現(xiàn)過程。

如果應(yīng)用要使用網(wǎng)絡(luò)操作,那么清單文件中應(yīng)該包含以下權(quán)限:

<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

選擇HTTP客戶端

大多數(shù)的Android應(yīng)用使用HTTP來發(fā)送、接收數(shù)據(jù)。Android中包含了兩個HTPP客戶端:HttpURLConnection及Apache的HTTP客戶端。兩者都支持HTTPS,上傳,下載,超時時間配置,IPv6,連接池。我們推薦在Gingerbread及以上的版本中使用HttpURLConnection。有關(guān)這個話題的更多討論信息,請參見博客Android’s HTTP Clients.

檢查網(wǎng)絡(luò)連接狀況

在嘗試連接到網(wǎng)絡(luò)之前,應(yīng)當(dāng)通過getActiveNetworkInfo()方法及isConnected()方法檢查網(wǎng)絡(luò)連接是否可用。要記得,設(shè)備可能處于不在網(wǎng)絡(luò)范圍的情況中,也可能用戶并沒有開啟WIFI或者移動數(shù)據(jù)。該話題的更多信息請參見 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}... }

在子線程中執(zhí)行網(wǎng)絡(luò)操作

網(wǎng)絡(luò)操作所用的時間通常是不確定的。為了防止由于網(wǎng)絡(luò)操作而引起的糟糕的用戶體驗,應(yīng)該將這個過程放入獨立的線程中執(zhí)行。AsyncTask類為這種實現(xiàn)提供了幫助。更多該話題的討論請參見Multithreading For Performance。

在下面的代碼段中,myClickHandler()方法調(diào)用了new DownloadWebpageTask().execute(stringUrl)。類DownloadWebpageTask是AsyncTask的子類。DownloadWebpageTask實現(xiàn)了AsyncTask的以下方法:

  • doInBackground()中執(zhí)行了downloadUrl()方法。它將Web頁的URL地址作為參數(shù)傳給了該方法。downloadUrl()方法會獲得并處理Web頁面的內(nèi)容。當(dāng)處理結(jié)束時,這個方法會將處理后的結(jié)果返回。
  • onPostExecute()獲得返回后的結(jié)果將其顯示在UI上。
public class HttpExampleActivity extends Activity {private static final String DEBUG_TAG = "HttpExample";private EditText urlText;private TextView textView;@Overridepublic 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> {@Overrideprotected 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.@Overrideprotected void onPostExecute(String result) {textView.setText(result);}}... }

上面的代碼執(zhí)行了以下操作:

  • 1.當(dāng)用戶按下按鈕時會調(diào)用myClickHandler()方法,應(yīng)用會將指定的URL地址傳遞給DownloadWebpageTask。
  • 2.DownloadWebpageTask的doInBackground()方法調(diào)用了downloadUrl()方法。
  • 3.downloadUrl()方法將獲得的URL字符串作為參數(shù)創(chuàng)建了一個URL對象。
  • 4.URL對象被用來與HttpURLConnection建立連接。
  • 5.一旦連接建立,HttpURLConnection會將獲取到的Web頁面內(nèi)容作為輸入流輸入。
  • 6.readIt()方法將輸入流轉(zhuǎn)換為String對象。
  • 7.最后onPostExecute()方法將String對象顯示在UI上。

連接與下載數(shù)據(jù)

在執(zhí)行網(wǎng)絡(luò)傳輸?shù)木€程中可以使用HttpURLConnection來執(zhí)行GET請求并下載輸入。在調(diào)用了connect()方法之后,可以通過getInputStream()方法獲得輸入流形式的數(shù)據(jù)。

在doInBackground()方法中調(diào)用了downloadUrl()方法。downloadUrl()方法將URL作為參數(shù)通過HttpURLConnection與網(wǎng)絡(luò)建立連接。一旦連接建立,應(yīng)用通過getInputStream()方法來接收字節(jié)流形式的數(shù)據(jù)。

// 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 queryconn.connect();int response = conn.getResponseCode();Log.d(DEBUG_TAG, "The response is: " + response);is = conn.getInputStream();// Convert the InputStream into a stringString 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()方法返回的是連接的狀態(tài)碼。該狀態(tài)碼可以用來獲取連接的其它信息。狀態(tài)碼為200則表明連接成功。

將字節(jié)流轉(zhuǎn)換為字符串

InputStream所讀取的是字節(jié)數(shù)據(jù)。一旦獲得InputStream對象,通常需要將其解碼或者轉(zhuǎn)化為其它類型的數(shù)據(jù)。比如,如果下載了一張圖片,則應(yīng)該將字節(jié)流轉(zhuǎn)碼為圖片:

InputStream is = null; ... Bitmap bitmap = BitmapFactory.decodeStream(is); ImageView imageView = (ImageView) findViewById(R.id.image_view); imageView.setImageBitmap(bitmap);

在上的示例中,InputStream代表了Web頁面的文本內(nèi)容。下面的代碼展示了如何將字節(jié)流轉(zhuǎn)換為字符串:

// 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); }

總結(jié)

以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:网络操作之网络连接的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。