private void loadImageFromUrl(String imageUrl, ImageView imageView) {
new Thread(() -> {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(input);
// 在 UI 线程更新 ImageView
imageView.post(() -> imageView.setImageBitmap(bitmap));
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
// AsyncTask 用于加载网络图片
private static class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
LoadImageTask(ImageView imageView) {
imageViewReference = new WeakReference<>(imageView);
}
@Override
protected Bitmap doInBackground(String... strings) {
String imageUrl = strings[0];
Bitmap bitmap = null;
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null && imageViewReference.get() != null) {
ImageView imageView = imageViewReference.get();
imageView.setImageBitmap(bitmap);
}
}
}
2024年安卓使用okhttp加载网络请求
最新推荐文章于 2024-11-08 13:58:32 发布