您的位置:首页 > 移动开发 > Android开发

Android多线程,让耗时的操作去后台,handler传递对象图片下载

2014-04-18 16:55 316 查看
public class ImageListAdapter extends BaseAdapter {

private Context context;
private String[] myImages = null;

public ImageListAdapter(Context context, String[] myImages) {
this.context = context;
this.myImages = myImages;
}

@Override
public int getCount() {
if(myImages==null){
return 0;
}
return myImages.length;
}

@Override
public Object getItem(int position) {
if(position < 0 || myImages == null || position>myImages.length){
return null;
}
return myImages[position];
}

@Override
public long getItemId(int position) {

return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

View item = null;
if(convertView!=null){
item = convertView;
}else{
item = View.inflate(context, R.layout.image_item, null);
}

final ImageView imageView = (ImageView)item.findViewById(R.id.image);
final String image = (String) getItem(position);
if(image==null){
return item;
}

//对每个图片地址创建一个线程
new Thread(){
public void run() {
Message msg=new Message();
msg.what=0;
Bitmap bitmap = getBitmap(image);
List list=new ArrayList();
list.add(bitmap);
list.add(imageView);
msg.obj=list;  //handler传递对象
handler.sendMessage(msg);
};
}.start();

return item;

}

protected Bitmap getBitmap(String imUrl) {
Bitmap bitmap = null ;
try{
URL picurl=new URL(imUrl);
HttpURLConnection conn = (HttpURLConnection) picurl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap= BitmapFactory.decodeStream(is);
is.close();
}catch(Exception e){
e.printStackTrace();
}

return bitmap;
}

private Handler handler=new Handler(){

public void handleMessage(Message msg) {
switch (msg.what) {
case 0:  //接到从线程内传来的图片bitmap和imageView.
//这里只是将bitmap传到imageView中就行了。只所以不在线程中做是考虑到线程的安全性
List list=(List) msg.obj;
Bitmap bitmap = (Bitmap)list.get(0);
ImageView iv = (ImageView)list.get(1);
iv.setImageBitmap(bitmap);

break;

default:
super.handleMessage(msg);
break;
}
};
};

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: