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

Android 使用線程下載網路圖片並更新 UI

編輯:關於 Android 程式設計

在 Android 中加載網路圖片時,不能直接在主線程中執行網絡請求,否則可能引發 ANR 或網絡異常。常見做法是開啟子線程下載圖片,再透過 Handler 把結果傳回主線程,最後更新 ImageView。

1. 添加網絡權限

首先需要在 AndroidManifest.xml 中聲明網絡權限。

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

2. 編寫布局

布局中放置一個按鈕與一個 ImageView,用於觸發加載並展示圖片。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="加載圖片" />

    <ImageView
        android:id="@+id/image1"
        android:layout_width="match_parent"
        android:layout_height="500dp" />

</LinearLayout>

3. 使用線程與 Handler

點擊按鈕後開啟新線程,在線程中訪問圖片 URL,將輸入流轉換為 Bitmap,然後通過 Handler 發送消息給主線程。

public class MainActivity extends AppCompatActivity {
    private Button button;
    private ImageView imageView;
    private String imagePath = "https://pica.nipic.com/2007-11-09/200711912453162_2.jpg";
    private final int IS_FINISH = 1;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bitmap bitmap = (Bitmap) msg.obj;
            imageView.setImageBitmap(bitmap);
        }
    };

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

        button = findViewById(R.id.button1);
        imageView = findViewById(R.id.image1);

        button.setOnClickListener(v -> new Thread(new MyClass()).start());
    }

    public class MyClass implements Runnable {
        @Override
        public void run() {
            Bitmap bitmap = null;
            try {
                URL url = new URL(imagePath);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream inputStream = connection.getInputStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Message message = Message.obtain();
            message.obj = bitmap;
            message.what = IS_FINISH;
            handler.sendMessage(message);
        }
    }
}

這種方式雖然簡單,但在實際項目中仍建議加入加載狀態、異常處理、緩存策略以及圖片壓縮,避免內存溢出。如果使用更現代的方式,也可以考慮使用 Glide、Picasso 或 Coil 等圖片加載庫。

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