Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網路圖片載入與顯示的完整實作

編輯:關於 Android 程式設計

幾乎每個應用都需要從網路抓取圖片並顯示出來。本文將實作一個這樣的例子:使用者在輸入框貼上圖片網址,點擊按鈕後,程式在子線程中下載圖片,再透過 Handler 更新到畫面的 ImageView 上。

效果預覽

界面包含三個控制項:一個 EditText、一個 Button 與一個 ImageView。

步驟一:佈局檔

<EditText
    android:id="@+id/picturepagh"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />
<Button
    android:id="@+id/btn"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="查看" />
<ImageButton
    android:id="@+id/imageView"
    android:layout_width="fill_parent"
    android:layout_height="200px" />

步驟二:在 MainActivity 中實作

點擊按鈕時啟動子線程下載,下載完成後透過 Handler 把 Bitmap 送回主線程更新畫面:

public class MainActivity extends Activity {
    private Button btn;
    private EditText path;
    private ImageView imgview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.btn);
        path = (EditText) findViewById(R.id.picturepagh);
        imgview = (ImageView) findViewById(R.id.imageView);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(runa).start(); // 在子線程中下載
            }
        });
    }
    public void setView() {
        String picturepath = path.getText().toString();
        try {
            byte[] data = ImageService.getImage(picturepath);
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); // 圖片工廠
            Message msg = new Message();
            msg.what = 0;
            msg.obj = bitmap;
            handler.sendMessage(msg);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "獲取圖片錯誤", 1).show();
        }
    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                updateImageView((Bitmap) msg.obj);
            }
        }
    };
    private Runnable runa = new Runnable() {
        @Override
        public void run() {
            setView();
        }
    };
    private void updateImageView(Bitmap bm) {
        imgview.setImageBitmap(bm);
    }
}

步驟三:建立 ImageService 圖片服務類

封裝一個透過 HttpURLConnection 抓取網路圖片位元組的方法:

public class ImageService {
    // 取得網路圖片的資料
    public static byte[] getImage(String picturepath) throws Exception {
        URL url = new URL(picturepath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 基於 http 協定的連線物件
        conn.setConnectTimeout(10);   // 10 秒逾時
        conn.setRequestMethod("GET");
        if (conn.getResponseCode() == 200) {
            InputStream ins = conn.getInputStream();
            return StreamTool.read(ins);
        }
        return null;
    }
}

步驟四:建立 StreamTool 流處理工具類

把輸入串流讀取為位元組陣列:

public class StreamTool {
    public static byte[] read(InputStream ins) throws Exception {
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = 0;
        while ((length = ins.read(buffer)) > -1) {
            outstream.write(buffer, 0, length);
        }
        outstream.close();
        return outstream.toByteArray();
    }
}

步驟五:加上網路權限

最後別忘了在清單檔中宣告網路權限,否則程式無法連線:

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

這個範例完整地串起了「子線程下載 → 位元組轉 Bitmap → Handler 更新 UI」的經典流程,是理解 Android 網路圖片載入機制的最佳入門實作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved