首页 > 代码库 > 基于AsyncTask的图片下载
基于AsyncTask的图片下载
有一阵子没有写程序,连基本的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();
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。