Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 入門:做一個查看伺服器圖片的應用

一、需求

假設有一台 Web 伺服器上放著一張圖片,Android 客戶端要能抓取並顯示出來;點擊「提交」後,就載入指定伺服器上的圖。

這裡有個關鍵眉角:不能用 localhost 代表本機,必須填入區網的 IP 位址,否則會丟出 Connection refused 之類的異常。

二、核心 API

先別忘了在 AndroidManifest.xml 加上:

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

抓取流程可以拆成七步:

  1. URL url = new URL("https://....."); — 把字串轉為 URL
  2. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  3. conn.setRequestMethod("GET"); — 指定請求方法
  4. conn.setReadTimeout(milliseconds); — 設定讀取逾時
  5. int code = conn.getResponseCode(); — 取得回應碼,200 為 OK,404 為無資源
  6. InputStream in = conn.getInputStream(); — 取得輸入串流
  7. Bitmap bitmap = BitmapFactory.decodeByteArray(byte[] data, int begin, int length); — 由 byte[] 還原為位圖

三、完整程式碼

伺服器端這裡用 Tomcat 7.0.6,搭建過程從略。

MainActivity.java

package org.xiazdong.view.image;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private EditText editText;
    private Button button;
    private ImageView imageView;

    private OnClickListener listener = new OnClickListener(){
        @Override
        public void onClick(View v) {
            Bitmap bitmap = null;
            try {
                bitmap = getImage(editText.getText().toString());
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "獲取圖片失敗", Toast.LENGTH_SHORT).show();
            }
            if (bitmap != null)
                imageView.setImageBitmap(bitmap);
            else
                Toast.makeText(MainActivity.this, "獲取圖片失敗", Toast.LENGTH_SHORT).show();
        }

        private Bitmap getImage(String path) throws Exception {
            URL url = new URL(path);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            byte[] data;
            con.setRequestMethod("GET");
            if (con.getResponseCode() == 200) {
                InputStream in = con.getInputStream();
                data = read2Byte(in);
                return BitmapFactory.decodeByteArray(data, 0, data.length);
            } else
                return null;
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editText = (EditText) this.findViewById(R.id.imagepath);
        button = (Button) this.findViewById(R.id.button);
        imageView = (ImageView) this.findViewById(R.id.imageview);
        button.setOnClickListener(listener);
    }

    private byte[] read2Byte(InputStream in) throws IOException {
        byte[] data;
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = in.read(buf)) != -1) {
            bout.write(buf, 0, len);
        }
        data = bout.toByteArray();
        return data;
    }
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="圖片路徑" />

    <!-- 此處不能用 localhost,一定要用 ip 位址 -->
    <EditText
        android:id="@+id/imagepath"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="https://192.168.0.103:8080/Server/logo.png" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提交" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageview" />

</LinearLayout>

實作上有兩點值得留意:read2Byte 用 1024 位元組的緩衝區迴圈讀完串流,比一次讀到底更省記憶體;另外真實專案裡網路請求應該移出主執行緒,這裡為了聚焦在 HttpURLConnection 的用法而寫在同一處,僅供入門參考。

Copyright © Linux教程網 All Rights Reserved