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; } }; }; }
相关文章推荐
- Android多线程——Handler (一) 实现图片下载
- Android多线程,让耗时的操作去后台运行吧
- Android多线程,让耗时的操作去后台运行吧
- Android多线程,让耗时的操作去后台运行吧
- Android–多线程之Handler下载图片源码
- Android多线程,让耗时的操作去后台运行吧
- Android多线程,让耗时的操作去后台运行吧
- Android底下多线程下载远程图片
- 线程对象Android 开发之多线程处理、Handler 详解
- Android:仿微博Listview与多线程功能(JSON、数据下载、图片加载、Listview、异步任务)
- 在Android中使用Handler和Thread线程执行后台操作
- 在Android中使用Handler和Thread线程执行后台操作
- android图片的上传、下载和一些缩放操作
- [转]Android底下多线程下载远程图片
- Android异步下载网络图片(其一:Handler)
- 转载 Android多线程下载远程图片
- Android异步下载网络图片(其一Handler)
- android 多线程下载图片
- 鱼鱼Chen之学写自己的apk(五)使用Handler完成Android里的多线程操作实例
- android handler 里面引用context有耗时操作是的正确打开方式