Android文檔學習05_網絡1

反向地理編碼是把處理經緯度座標轉換爲人們能夠讀取的地址信息。這裏使用的是Geocoder APIhtml


大多數網絡鏈接的Android應用使用HTTP發送和接受數據,Android包括兩個HTTP客戶端:HttpURLConnection和ApacheHttpClient,它們支持HTTPS,流上傳和下載
java


檢查網絡鏈接


ConnectivityManager connMgr = (ConnectivityManager) 
        getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        // 獲取數據
    }...
android



網絡操做涉及不可預知的延遲,爲了防止不良的用戶體驗,一般的作法是從UI中獨立出線程去執行網絡鏈接操做。AsyncTask類提供了最簡單的從UI線程中獨立出一個新任務的方式。
web


if (networkInfo != null && networkInfo.isConnected()) {
            new DownloadWebpageText().execute(stringUrl);
        } else {
            textView.setText("No network connection available.");
        }
apache



// 使用AsyncTask建立一個獨立於主UI線程以外的任務. 並使用URL字符串建立一個HttpUrlConnection對象。 
     // 一旦鏈接創建,AsyncTask則將網頁內容做爲一個InputStream對象進行下載。
     // 最終,InputStream對象會被轉換爲一個字符串對象,並被AsyncTask的onPostExecute方法顯示在UI上。
     private class DownloadWebpageText extends AsyncTask {
        @Override
        protected String doInBackground(String... urls) {
 
            // 參數來自execute(),調用params[0]獲得URL
            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "沒法獲取網頁,URL可能無效!Unable to retrieve web page. URL may be invalid.";
            }
        }
        // onPostExecute顯示AsyncTask結果.
        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
       }
    }
網絡


// 給一個URL,創建HttpUrlConnection對象並做爲流對象(InputStream)獲取網頁數據,最後返回一個字符串。
private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // 先顯示獲取到的前500個字節
    // 網頁內容
    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);
        // 開始查詢
        conn.connect();
app

//getResponseCode()方法返回的是鏈接狀態碼
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();
 
        // 將InputStream轉化爲string
        String contentAsString = readIt(is, len);
        return contentAsString;
 
    // 確保當app用完InputStream對象後關閉它。
    } finally {
        if (is != null) {
            is.close();
        } 
    }
}
 
ide


下載了一個圖像數據,你可能要將其轉碼而後像如下方式顯示:
編碼

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

imageView.setImageBitmap(bitmap);



將InputStream對象轉換爲String(字符對象),而後activity在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); }

相關文章
相關標籤/搜索