Bitmap 图片异步加载

来源:互联网 发布:淘宝买托福答案被骗 编辑:程序博客网 时间:2024/05/22 08:15
package com.example.zhangjinling0901;

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

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class ImageUtil {
   ImageView imageView;

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


     /**
      * 给imageView控件加载图片
      */
     public void getImage(final String path, ImageView imageView){
         this.imageView = imageView;

         new Thread(){
             @Override
             public void run() {
                 try {
                     URL url = new URL(path);

                     HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                     connection.setRequestMethod("GET");
                     connection.setReadTimeout(5000);
                     connection.setConnectTimeout(5000);

                     //响应的状态码
                     int responseCode = connection.getResponseCode();
                     if (responseCode == 200){
                         InputStream inputStream = connection.getInputStream();

                         //转为bitmap
                         Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                         //向Handler发送数据
                         Message message = Message.obtain();
                         message.what = 0;
                         message.obj = bitmap;
                         handler.sendMessage(message);
                     }

                 } catch (Exception e) {
                     e.printStackTrace();
                 }

             }
         }.start();

     }
}