Android 图片异步加载

jopen 10年前

所谓图片异步加载,意思是不用一次把图片全部加载完,你可以叫它延迟加载,缓冲加载都行。

看看你有没有这种需求:某篇文章图片很多,如果在载入文章时就载入所有图片,无疑会延缓载入速度,让用户等更久,所以,我想找这样一种插件,让网页只加载浏览器视野范围内的图片,没出现在范围内的图片就暂不加载,等用户滑动滚动条时再逐步加载。lazyload就是用来实现这种效果。

package com.example.demo1;    import java.io.File;  import java.io.FileOutputStream;  import java.io.IOException;  import java.io.InputStream;  import java.io.OutputStream;  import java.net.HttpURLConnection;  import java.net.URL;  import java.util.ArrayList;    import EntityBen.GoodsItem;  import android.content.Context;  import android.graphics.Bitmap;  import android.graphics.BitmapFactory;  import android.os.AsyncTask;  import android.os.Environment;  import android.view.LayoutInflater;  import android.view.View;  import android.view.ViewGroup;  import android.widget.BaseAdapter;  import android.widget.ImageView;  import android.widget.TextView;    public class MyAdapter extends BaseAdapter {      Context context ;   ArrayList<GoodsItem> list ;      int index ;           public MyAdapter(Context con, ArrayList<GoodsItem> list) {    super();    this.context = con;    this.list = list;   }     @Override   public int getCount() {    // TODO Auto-generated method stub    return list.size();   }     @Override   public Object getItem(int position) {    // TODO Auto-generated method stub    return list.get(position);   }     @Override   public long getItemId(int position) {    // TODO Auto-generated method stub    return 0;   }     @Override   public View getView(int position, View convertView, ViewGroup parent) {    // TODO Auto-generated method stub     index = position ;        View view = convertView ;    ViewHolder vH;    if(view == null){     System.out.println("dddddddddd"+context);     LayoutInflater inflater = LayoutInflater.from(context);     view = inflater.inflate(R.layout.tuangou_lv, null);     vH = new ViewHolder();     vH.name = (TextView) view.findViewById(R.id.goods_name);     vH.info = (TextView) view.findViewById(R.id.goods_infor);     vH.costPrice = (TextView) view.findViewById(R.id.cost_price);     vH.oriPrice = (TextView) view.findViewById(R.id.ori_price);     vH.moods = (TextView) view.findViewById(R.id.moods);     vH.imgtask = (ImageView) view.findViewById(R.id.goods_img);     view.setTag(vH);         }else     vH = (ViewHolder) view.getTag();          vH.name.setText(list.get(position).getName());    vH.info.setText(list.get(position).getInfo());    vH.costPrice.setText(list.get(position).getCostprice() + "");    vH.oriPrice.setText(list.get(position).getOriprice() + "");    vH.moods.setText(list.get(position).getMoods() + "人");                //当前行的图片路径 例如:http://192.168.0.148:9999/Music/aaa.jpg      String fileurl = list.get(position).getImageUrl();      //文件操作类实例化      FileUtils f = new FileUtils();      //通过字符串操作获得当前的图片名称 ( aaa.jpg)      String fileName = fileurl.substring(fileurl.lastIndexOf("/") + 1);      // /mnt/sdcard/tt/aaa.jpg      String filePath = f.GetSDPATH() + "tt/"+fileName;            //验证当前图片是否已经存在 /mnt/sdcard/tt/ 中            if(f.IsFileExists("tt/"+fileName)){//如果存在             vH.imgtask.setImageBitmap(BitmapFactory.decodeFile(filePath));            }else{//如果不存在             vH.downloadImage=new DownLoadImage(vH.imgtask);             vH.downloadImage.execute(list.get(position).getImageUrl());            }                 return view;           }       public static class ViewHolder{     private DownLoadImage downloadImage ;     private ImageView  imgtask;     private TextView name , info , costPrice ,oriPrice , moods;    }      private class  DownLoadImage extends AsyncTask<String, Void, Bitmap>{         Bitmap drawable;    ImageView imageView;    DownLoadImage (ImageView img){     this.imageView=img;    }    /**     * 此函数相当于 run函数     */    @Override    protected Bitmap doInBackground(String... params) {     DownImg fileDownload=new DownImg();      //调用图片下载函数,将图片下载到本地,并返回此图片的本地路径         String TalkPath = fileDownload.DownLoadFile(params[0], "tt");                  drawable = BitmapFactory.decodeFile(TalkPath);     return drawable; //相当于 Message    }        /**     * 当任务执行之前开始调用此方法,可以在这里显示进度对话框     */    @Override    protected void onPreExecute() {     super.onPreExecute();     System.out.println("异步加载开始了");    }               /**     * 此方法在主线程执行,任务执行的结果作为此方法的参数返回。     */    @Override    protected void onPostExecute(Bitmap result) {     // TODO Auto-generated method stub     super.onPostExecute(result);     System.out.println("异步执行完毕了,返回");     if (result!=null) {      imageView.setImageBitmap(drawable);     }    }    }         public class DownImg {      HttpURLConnection httpconn = null;      public String DownLoadFile(String fileurl, String path) {     InputStream inputStream = null;     OutputStream outputStream = null;     File file = null;     String fileName = "";     String imgPath = "";     try {      fileName = fileurl.substring(fileurl.lastIndexOf("/") + 1);      FileUtils fileUtils = new FileUtils();      imgPath =fileUtils.GetSDPATH() +  path + "/" + fileName;      System.out.println(fileurl + "   " + imgPath);      if (fileUtils.IsFileExists(path + "/" + fileName)) {       System.out.println("已存在此图片,无需下载");       return imgPath;      }      URL url = new URL(fileurl);// 获得或者确定下载的路径      HttpURLConnection httpconnCon = (HttpURLConnection) url        .openConnection();      inputStream = httpconnCon.getInputStream();// 获得字节流      fileUtils.CreateSDDir(path);// 确定下载路径(创建你需要的文件夹)      file = fileUtils.CreateSDFile(path + "/" + fileName);      System.out.println("ddddd---" + file);      outputStream = new FileOutputStream(file);      byte buffer[] = new byte[4 * 1024];      int length = 0;      while ((length = inputStream.read(buffer)) != -1) {       outputStream.write(buffer, 0, length);      }      outputStream.flush();     } catch (Exception e) {      return null;     } finally {      try {       // inputStream.close();       // outputStream.close();      } catch (Exception e2) {       e2.printStackTrace();      }     }     return imgPath;      }           }      public class FileUtils {    private String SDPATH;      public FileUtils() {     SDPATH = Environment.getExternalStorageDirectory() + "/";     //"/mnt/sdcard/"    }      /**     * 获得当前系统的SDPATH路径字符     * */    public String GetSDPATH() {     return SDPATH;    }      /**     * 在SD卡上创建文件     * */    public File CreateSDFile(String fileName) throws IOException {     File file = new File(SDPATH + fileName);     boolean isCreate = file.createNewFile();     return file;    }      /**     * 在SD卡上创建文件夹     * */    public File CreateSDDir(String dirName) {     File file = new File(SDPATH + dirName);     boolean isCreateDir = file.mkdir();     return file;    }      /**     * 判断文件是否存在     * */    public boolean IsFileExists(String fileName) {     //"/mnt/sdcard/hhh/aaa.mp3"     File file = new File(SDPATH + fileName);     return file.exists();    }         }    }