Android 异步加载一张网络图片

/**
 * 从网络上异步加载单个图片
 * 
 *  
 */
public class LoadOneImageFromNet extends Activity {
	Button button;
	ImageView iView;
	String imageUrl = "http://image.club.china.com/twhb/7137652/2012/11/17/1353147018580.jpg";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.loadoneimagefromnet);
		button = (Button) this.findViewById(R.id.oneImageButton);
		iView = (ImageView) this.findViewById(R.id.oneImage);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				executeAsyncTask();

			}
		});
	}
	/**
  * 启动并执行异步加载任务
  */
	public void executeAsyncTask() {
		BitMapWorkTask bitMapWorkTask = new BitMapWorkTask(iView);
		iView.setImageResource(R.drawable.ic_launcher);// 设置加载等待图片
		bitMapWorkTask.execute(imageUrl);
		Log.i("info", "图片加载完成!");
	}

	/**
	 * 计算图片缩小比例
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;
		if (height > reqHeight || width > reqWidth) {
			final int halfHeight = height / 2;
			final int halfWidth = width / 2;
			while ((halfHeight / inSampleSize) > reqHeight
					&& (halfWidth / inSampleSize) > reqWidth) {
				inSampleSize *= 2;
			}
		}
		return inSampleSize;
	}

	/**
	 * 从网络加载图片
	 * 
	 * @param uri
	 * @return
	 */
	public Bitmap decodeStreamBitmap(String uri) {
		Bitmap bitmap = null;
		HttpGet get = new HttpGet(uri);
		try {
			HttpClient client = new DefaultHttpClient();
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			InputStream inputStream = entity.getContent();
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(inputStream, null, options);
			int inSampleSize = calculateInSampleSize(options, 160, 130);
			options.inSampleSize = inSampleSize;
			options.inJustDecodeBounds = false;
			response = client.execute(get);
			entity = response.getEntity();
			inputStream = entity.getContent();
			bitmap = BitmapFactory.decodeStream(inputStream, null, options);

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

	/**
	 * 异步加载数据类
	 * 
	 * 	  
	 */
	class BitMapWorkTask extends AsyncTask<String, Void, Bitmap> {
		// 定义一个对ImageView的弱引用,目的是异步线程不会干扰GC对ImageView对象的回收
		WeakReference<ImageView> imageReference;
		

		public BitMapWorkTask(ImageView imageView) {
			imageReference = new WeakReference<ImageView>(imageView);
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			return decodeStreamBitmap(params[0]);
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			if (result != null && imageReference != null) {
				ImageView imageView = imageReference.get();
				if (imageView != null) {
					imageView.setImageBitmap(result);
				}
			}
		}
	}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/oneImageButton"
        android:layout_width="fill_parent"
        android:layout_height="50dp" android:text="load image from Internet"/>

    <ImageView
        android:id="@+id/oneImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true" />

</LinearLayout>

 效果图(点击按钮加载图片):




 
 

猜你喜欢

转载自deep-fish.iteye.com/blog/2032897