有一阵子没有写程序,连基本的AsyncTask用法都记不清楚了,复习一下于是有了下面的图片加载类。
package com.hitech.download; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import android.widget.ImageView; public class ImageLoader { private static final String TAG = "ImageLoader"; private String url = null; private ImageView imageView = null; public ImageLoader() { } public ImageLoader(String url, ImageView imageView) { this.url = url; this.imageView = imageView; } public void execute() { new Loader().execute(new String[] { url }); } public class Loader extends AsyncTask<String, String, Bitmap> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Bitmap doInBackground(String... params) { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(params[0]); Log.e(TAG, params[0]); try { HttpResponse response = client.execute(request); System.out.println(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == 200) { return BitmapFactory.decodeStream(response.getEntity().getContent()); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap bm) { super.onPostExecute(bm); // imageView.setImageBitmap(bm); imageView.setImageBitmap(bm); } } }
调用只需要一行简单的代码就能完成图片的加载。
new ImageLoader("http://192.168.0.251/welcome.png", imageView1).execute(); new ImageLoader("http://192.168.0.251/genymotion.png", imageView2).execute();