AsyncTask异步加载图片


package com.example.wechat;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class ImageAsyncTask extends AsyncTask<String, Integer, Bitmap> {
	private ImageView img;

	public ImageAsyncTask(ImageView img) {
		super();
		this.img = img;
	}

	@Override
	protected Bitmap doInBackground(String... params) {
		// TODO Auto-generated method stub
		try {
			HttpURLConnection hcn = (HttpURLConnection) new URL(params[0])
					.openConnection();
			int code = hcn.getResponseCode();
			if (code == 200) {
				BufferedInputStream stream = new BufferedInputStream(
						hcn.getInputStream());
				Bitmap bitmap = BitmapFactory.decodeStream(stream);
				stream.close();
				return bitmap;
			}else {
				Log.i("jx", "code:"+code);
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		img.setImageBitmap(result);//给图片以Bitmap形式赋值
	}

}

调用方法

new ImageAsyncTask (图片对象).execute(图片路径);


猜你喜欢

转载自blog.csdn.net/qq_42120002/article/details/80188089