<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                > 編寫:[kesenhoo](https://github.com/kesenhoo) - 原文:[http://developer.android.com/training/basics/network-ops/connecting.html](http://developer.android.com/training/basics/network-ops/connecting.html) 這一課會演示如何實現一個簡單的連接到網絡的程序。它提供了一些你在創建即使最簡單的網絡連接程序時也應該遵循的最佳示例。請注意,想要執行本課的網絡操作首先需要在程序的manifest文件中添加以下permissions: ~~~ <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> ~~~ ### 1)選擇一個HTTP Client 大多數連接網絡的Android app會使用HTTP來發送與接受數據。Android提供了兩種HTTP clients: [HttpURLConnection](http://developer.android.com/reference/java/net/HttpURLConnection.html) 與Apache [HttpClient](http://developer.android.com/reference/org/apache/http/client/HttpClient.html)。二者均支持HTTPS ,流媒體上傳和下載,可配置的超時, IPv6 與連接池(connection pooling). **推薦從Android 2.3 Gingerbread版本開始使用 HttpURLConnection** 。關于這部分的更多詳情,請參考 [Android's HTTP Clients](http://android-developers.blogspot.com/2011/09/androids-http-clients.html)。 ### 2)檢查網絡連接 在你的app嘗試連接網絡之前,應通過函數[getActiveNetworkInfo](http://developer.android.com/reference/android/net/ConnectivityManager.html#getActiveNetworkInfo())和[isConnected](http://developer.android.com/reference/android/net/NetworkInfo.html#isConnected())檢測當前網絡是否可用。請注意,設備可能不在網絡覆蓋范圍內,或者用戶可能關閉Wi-Fi與移動網絡連接。關于這部分的更多詳情,請參考 [管理網絡的使用情況](#) ~~~ 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 } ... } ~~~ ### 3)在一個單獨的線程中執行網絡操作 網絡操作會遇到不可預期的延遲。為了避免造成不好的用戶體驗,總是在UI線程之外執行網絡操作。[AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html) 類提供了一種簡單的方式來處理這個問題。關于更多的詳情,請參考:[Multithreading For Performance](http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html). 在下面的代碼示例中,myClickHandler() 方法會執行new DownloadWebpageTask().execute(stringUrl).DownloadWebpageTask是AsyncTask的子類,它實現了下面兩個方法: - [doInBackground()](http://developer.android.com/reference/android/os/AsyncTask.html) 執行 downloadUrl()方法。它以Web頁面的URL作為參數,方法downloadUrl() 獲取并處理網頁返回的數據,執行完畢后,返回一個結果字符串。 - [onPostExecute()](http://developer.android.com/reference/android/os/AsyncTask.html) 接受結果字符串并把它顯示到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 DownloadWebpageText().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 DownloadWebpageText extends AsyncTask { @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(),app將指定的URL傳給[AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html)的子類DownloadWebpageTask.2.[AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html)的[doInBackground()](http://developer.android.com/reference/android/os/AsyncTask.html#doInBackground(Params...))方法調用downloadUrl()方法.3.downloadUrl()以一個URL字符串作為參數,并用它創建一個[URL](http://developer.android.com/reference/java/net/URL.html)對象.4.這個[URL](http://developer.android.com/reference/java/net/URL.html)對象被用來創建一個[HttpURLConnection](http://developer.android.com/reference/java/net/HttpURLConnection.html).5.一旦建立連接,[HttpURLConnection](http://developer.android.com/reference/java/net/HttpURLConnection.html)對象將獲取Web頁面的內容并得到一個[InputStream](http://developer.android.com/reference/java/io/InputStream.html).6.[InputStream](http://developer.android.com/reference/java/io/InputStream.html)被傳給readIt()方法,該方法將流轉換成字符串.7.最后,[AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html)的[onPostExecute()](http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result))方法將字符串展示在main [activity](# "An activity represents a single screen with a user interface.")的UI上. ### 4)連接并下載數據 在執行網絡交互的線程里面,你可以使用 [HttpURLConnection](http://developer.android.com/reference/java/net/HttpURLConnection.html) 來執行一個 GET 類型的操作并下載數據。在你調用 connect()之后,你可以通過調用getInputStream()來得到一個包含數據的[InputStream](http://developer.android.com/reference/java/io/InputStream.html) 對象。 在下面的代碼示例中, [doInBackground()](http://developer.android.com/reference/android/os/AsyncTask.html#doInBackground(Params...)) 方法會調用downloadUrl(). 這個 downloadUrl() 方法使用給予的URL,通過 [HttpURLConnection](http://developer.android.com/reference/java/net/HttpURLConnection.html) 連接到網絡。一旦建立連接后,app就會使用 getInputStream() 來獲取包含數據的[InputStream](http://developer.android.com/reference/java/io/InputStream.html)。 ~~~ // 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() 會返回連接狀態碼( status code). 這是一種獲知額外網絡連接信息的有效方式。status code 是 200 則意味著連接成功. ### 5)將輸入流(InputStream)轉換為字符串(String) [InputStream](http://developer.android.com/reference/java/io/InputStream.html) 是一種可讀的byte數據源。如果你獲得了一個 [InputStream](http://developer.android.com/reference/java/io/InputStream.html), 通常會進行解碼(decode)或者轉換為目標數據類型。例如,如果你是在下載圖片數據,你可能需要像下面這樣解碼并展示它: ~~~ InputStream is = null; ... Bitmap bitmap = BitmapFactory.decodeStream(is); ImageView imageView = (ImageView) findViewById(R.id.image_view); imageView.setImageBitmap(bitmap); ~~~ 在上面演示的示例中,[InputStream](http://developer.android.com/reference/java/io/InputStream.html) 包含的是web頁面的文本內容。下面會演示如何把 [InputStream](http://developer.android.com/reference/java/io/InputStream.html) 轉換為字符串,以便顯示在UI上。 ~~~ // 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); } ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看