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

把網絡圖片顯示到 ImageView:線程與 UI 更新該怎麼分工

編輯:關於 Android 程式設計

寫這篇的時候我正在參與一個網絡調用密集的項目。回想剛接觸 Android 時也卡在這個問題上,網上搜到的不少示例直接把網絡請求寫在 onCreate 裡——那個思路是有問題的。網絡訪問必須異步進行,不能阻塞主線程,否則在 Honeycomb 之後會直接物流成本 ANR 或 NetworkOnMainThread 異常。

下面把示例改寫為線程化的正確版本。

Activity 代碼

public class MainActivity extends Activity {

    private ImageView imageView;
    private String picturePath = "https://content.52pk.com/files/100623/2230_102437_1_lit.jpg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = returnBitMap(picturePath);
                // 不能在子線程直接操作 UI,post 回主線程
                imageView.post(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }

    private Bitmap returnBitMap(String url) {
        URL myFileUrl = null;
        Bitmap bitmap = null;
        HttpURLConnection conn = null;
        InputStream is = null;
        try {
            myFileUrl = new URL(url);
            conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try { is.close(); } catch (IOException e) { e.printStackTrace(); }
            }
            if (conn != null) conn.disconnect();
        }
        return bitmap;
    }

    private void initView() {
        imageView = (ImageView) findViewById(R.id.picture);
    }
}

布局文件

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/display_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

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

另外必須在 AndroidManifest.xml 中加入 android.permission.INTERNET 權限。

為什麼要 post 回主線程

Android 有一條鐵律:只有創建某個 View 的線程才能修改它。子線程拿到 Bitmap 後不能直接 setImageBitmap,常見的三種切換方式:

  • view.post(Runnable):最輕量,適合單次更新;
  • runOnUiThread(Runnable):Activity 提供的便捷方法;
  • Handler:需要頻繁通信或跨組件時更靈活。

這份代碼還不夠好在哪

它能跑,但離生產可用還差幾步:

  • 沒有快取——列表反覆滑動會反覆下載同一張圖,必須加內存快取與磁盤快取;
  • 沒有做壓縮——直接 decodeStream 原圖,大圖必然 OOM,應按控件尺寸做 inSampleSize 降採樣;
  • 沒有做錯亂處理——列表快速滑動時,後返回的舊請求會覆蓋新圖,需要用 tag 或 URL 比對來丟棄過期結果;
  • 沒有取消機制——Activity 銷毀後線程仍在跑,存在內存洩漏風險。

這些問題,正是成熟圖片加載庫(Glide、Fresco、Picasso)替你解決的事情。理解原理之後,實戰中直接用它們即可。

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