图片异步加载AsyncTask以及ListView中item加载图片缓存

当LIstView加载多张图片时使用Handler+Runnable有点不现实,可以用谷歌的AsyncTask,另外,如果所需加载的图片不需要很精细的控制的话也可以采用AsyncTask,还有就是Listview加载的图片将其存入缓存中,暂且没写将其存在sd卡中,如果每次刷新Listview都要加载图片那么用户体验和程序的性能,下面附上代码:

SingleImageTaskUtil.java单个或者多个不要求对图片进行精细操作的话可以使用此工具类

package com.loulijun.utils;


import java.io.IOException;
import java.io.InputStream;
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.support.v4.util.LruCache;
import android.widget.ImageView;


public class SingleImageTaskUtil extends AsyncTask<String, Void, Bitmap> {


private ImageView iv;


public SingleImageTaskUtil(ImageView iv) {
this.iv = iv;
}


@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bitmap = null;
try {
bitmap = SimpleImageLoader.getBitmap(params[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return bitmap;
}


@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);


if (result != null) {
iv.setImageBitmap(result);
}
}


@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}


public static class SimpleImageLoader {
public static Bitmap getBitmap(String urlStr) throws IOException {
Bitmap bitmap;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");//用户可以根据不同的需要选择不同的方法get或者post请求
conn.setReadTimeout(5 * 1000);
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
}


}


ListViewImageTaskUtil.java当用户选择加载图片到Listview中可以选择此工具类操作,下面附上工具里代码,以及Listview的Adapter中的操作代码

package com.loulijun.utils;


import java.io.IOException;
import java.io.InputStream;
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.support.v4.util.LruCache;
import android.widget.ImageView;


public class ListViewImageTaskUtil extends AsyncTask<String, Void, Bitmap> {


private ImageView iv;
private LruCache<String, Bitmap> lruCache;//定义一个缓存区,程序被系统分配的


public ListViewImageTaskUtil(ImageView iv) {
this.iv = iv;
}


public ListViewImageTaskUtil(ImageView iv, LruCache<String, Bitmap> lruCache) {
super();
this.iv = iv;
this.lruCache = lruCache;
}


@Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bitmap = null;
try {
bitmap = SimpleImageLoader.getBitmap(params[0]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addBitmapToMemoryCache(params[0], bitmap);
return bitmap;
}


@Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);


if (result != null) {
iv.setImageBitmap(result);
}
}


@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}


private void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemoryCache(key) == null) {
lruCache.put(key, bitmap);
}
}


public Bitmap getBitmapFromMemoryCache(String key) {
return lruCache.get(key);
}


public static class SimpleImageLoader {
public static Bitmap getBitmap(String urlStr) throws IOException {
Bitmap bitmap;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5 * 1000);
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
}


}


MyAdapter.java下面是Adapter代码

package com.loulijun.adapter;


import java.util.List;


import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.loulijun.bean.CommondBean;
import com.loulijun.logindemo.R;
import com.loulijun.utils.ListViewImageTaskUtil;


public class MyAdapter extends BaseAdapter {


private Context context;


private List<CommondBean> commondBeans;


// 获取当前应用程序所分配的最大内存
private final int maxMemory = (int) Runtime.getRuntime().maxMemory();
// 只用五分之一用来做图片缓存
private final int cacheSize = maxMemory / 5;


private LruCache<String, Bitmap> mLruCache = new LruCache<String, Bitmap>(
cacheSize) {


// 重写sizeof()方法
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// TODO Auto-generated method stub
// 这里用多少kb来计算
return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
}


};


public MyAdapter(Context context, List<CommondBean> commondBeans) {


this.context = context;
this.commondBeans = commondBeans;
}


@Override
public int getCount() {
// TODO Auto-generated method stub
return commondBeans.size();
}


@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return commondBeans.get(position);
}


@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub


View view = convertView;


ViewHolder holder = null;


if (view == null) {
view = LayoutInflater.from(context).inflate(
R.layout.item_listview_commond, null);


holder = new ViewHolder();
view.setTag(holder);


holder.user_img = (ImageView) view.findViewById(R.id.userimg);
holder.user_detail = (TextView) view.findViewById(R.id.detail);
holder.user_name = (TextView) view.findViewById(R.id.name);
holder.user_good = (Button) view.findViewById(R.id.good);
holder.user_good.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub


Toast.makeText(context, "32个赞!", Toast.LENGTH_SHORT).show();


}
});
holder.user_poor = (Button) view.findViewById(R.id.poor);
holder.user_poor.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "贬低一个!", Toast.LENGTH_SHORT).show();
}
});
holder.user_hot = (Button) view.findViewById(R.id.hot);
holder.user_hot.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "更加火爆!", Toast.LENGTH_SHORT).show();
}
});
holder.user_share = (Button) view.findViewById(R.id.share);
holder.user_share.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "分享成功!", Toast.LENGTH_SHORT).show();
}
});
holder.good = (TextView) view.findViewById(R.id.goodtext);
holder.poor = (TextView) view.findViewById(R.id.poortext);
holder.hot = (TextView) view.findViewById(R.id.hottext);
holder.share = (TextView) view.findViewById(R.id.sharetext);


} else {
holder = (ViewHolder) convertView.getTag();
}


holder.user_detail.setText(commondBeans.get(position).getUserDetail());
holder.user_name.setText(commondBeans.get(position).getUserName());
holder.good.setText(commondBeans.get(position).getGood());
holder.poor.setText(commondBeans.get(position).getPoor());
holder.hot.setText(commondBeans.get(position).getHot());
holder.share.setText(commondBeans.get(position).getShare());
// 多任务处理加载图片
// ListViewImageTaskUtil imageTask = new ListViewImageTaskUtil(holder.user_img);
// imageTask.execute(commondBeans.get(position).getUserImg());
loadBitmap(commondBeans.get(position).getUserImg(), holder.user_img);
return view;
}


static class ViewHolder {
ImageView user_img;
TextView user_name;
TextView user_detail;
TextView good;
TextView poor;
TextView hot;
TextView share;
Button user_good;
Button user_poor;
Button user_hot;
Button user_share;
}


private void loadBitmap(String urlStr, ImageView image) {


ListViewImageTaskUtil asyncLoader = new ListViewImageTaskUtil(image, mLruCache);// 一个异步图片加载对象
Bitmap bitmap = asyncLoader.getBitmapFromMemoryCache(urlStr);// 首先从内存缓存中获取图片
if (bitmap != null) {
image.setImageBitmap(bitmap);// 如果缓存中存在这张图片则直接设置给ImageView
} else {
image.setImageResource(R.drawable.dufu);// 否则先设置成默认的图片
asyncLoader.execute(urlStr);// 然后执行异步任务AsycnTask 去网上加载图片
}
}


}


这两个工具类可以满足大部分的需求,如需对图片进行更为精细的操作大家可以自定义handler+Runnable

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值