android ListView 異步下載圖片 優化一

源碼:http://download.csdn.net/detail/songconglai/4667087


public class MainActivity extends Activity {

    private ListView listView = null;
    private AdapterListView adapterListView = null;
    private List<Person> listPerson;
    private String[] strURL = {
            "http://e.hiphotos.baidu.com/space/pic/item/aa64034f78f0f7364b7c6a840a55b319eac413b0.jpg",
            "http://fmn.rrimg.com/fmn060/xiaozhan/20120510/1225/x_large_nDFG_5204000016531261.jpg",
            "http://fmn.rrimg.com/fmn059/xiaozhan/20120509/1605/x_large_MksE_36ed000088981262.jpg",
            "http://fmn.rrimg.com/fmn065/xiaozhan/20120509/1415/x_large_6JaY_1a8400008b281262.jpg",
            "http://list.image.baidu.com/t/image_category/galleryimg/menstar/hk/wang_li_hong.jpg",
            "http://list.image.baidu.com/t/image_category/galleryimg/menstar/hk/wu_zun.jpg",
            "http://list.image.baidu.com/t/image_category/galleryimg/menstar/hk/he_run_dong.jpg",
            "http://list.image.baidu.com/t/image_category/galleryimg/menstar/hk/jin_cheng_wu.jpg",
            "http://list.image.baidu.com/t/image_category/galleryimg/menstar/hk/wu_yan_zu.jpg"
    };
    private String[] strName = { "song", "cong", "lai", "scl","5","6","7","8","9"};
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnNext = (Button) findViewById(R.id.btnToOtherActivity);
        listView = (ListView) findViewById(R.id.listViewItem01);
        listPerson = getPerson();
        adapterListView = new AdapterListView(MainActivity.this,listPerson,listView);
        listView.setAdapter(adapterListView);
        
        btnNext.setOnClickListener(new View.OnClickListener() {
            
            public void onClick(View v) {
                Intent intent = new Intent();  
                intent.setClass(MainActivity.this, NextActivity.class);  
                startActivity(intent);
            }
        });
    }
    private List<Person> getPerson() {
        List<Person> list = new ArrayList<Person>();
        for (int i = 0; i < strURL.length; i++) {
            Person person = new Person(strName[i], i + 20, strURL[i]);
            list.add(person);
        }
        return list;
    }
}

public class AdapterListView extends BaseAdapter {
    private LayoutInflater mlayoutInflater;
    private List<Person> list;
    private ListView listView = null;
    private AsyncDrawableLoader asyncDrawableLoader;
    public AdapterListView(Context context,List<Person> list,ListView listView) {

        mlayoutInflater = LayoutInflater.from(context);
        this.list = list;
        this.listView = listView;
        asyncDrawableLoader = new AsyncDrawableLoader();
    }

    public int getCount() {
        return list.size();
    }

    public Object getItem(int position) {
        return list.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView == null || convertView.getTag() == null){
            convertView = mlayoutInflater.inflate(R.layout.list_item01, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
        Person person = list.get(position);

        holder.personIcon.setTag(person.getStrUrlImageAddress());
        holder.personName.setText(person.getStrPersonName());
        holder.personAge.setText(person.getIntPersonAge() + "");
        holder.btnmore.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                // TODO Auto-generated method stub
                
            }
        });

        Drawable drawable = asyncDrawableLoader.loadDrawable(person.getStrUrlImageAddress(),
                new ImageCallBack() {
            
                    public void imageLoad(String strurl,Drawable drawable) {
                        ImageView imageListView = (ImageView) listView.findViewWithTag(strurl);
                        
                        if (imageListView != null && drawable !=null) {
                            System.out.println("imagecallBack");
                            imageListView.setBackgroundDrawable(drawable);
                        }
                    }
                });
        if(drawable == null){
            holder.personIcon.setBackgroundResource(R.drawable.ic_launcher);
        }else{
            holder.personIcon.setBackgroundDrawable(drawable);
        }
        return convertView;
    }
    
    private class ViewHolder{
        ImageView personIcon;
        TextView personName;
        TextView personAge;
        Button btnmore;

        public ViewHolder(View view) {
            this.personIcon = (ImageView) view.findViewById(R.id.ItemImage);
            this.personName = (TextView) view.findViewById(R.id.ItemTitle);
            this.personAge = (TextView) view.findViewById(R.id.ItemText);
            this.btnmore = (Button) view.findViewById(R.id.ItemBtn);
        }
    }
}

public class AsyncDrawableLoader {


    private File cachefile;
    private HashMap<String, SoftReference<Drawable>> imageCache;
    private static ExecutorService executor = Executors.newFixedThreadPool(5);


    public AsyncDrawableLoader() {
        System.out.println("AsyncDrawableLoader");
        if (cachefile == null) {
            cachefile = FileOperate.isExistsFile();
        }
        if (imageCache == null) {
            imageCache = new HashMap<String, SoftReference<Drawable>>();
            
        }
    }


    public Drawable loadDrawable(final String imageURL,
            final ImageCallBack imageCallBack) {
        final String strfilename = MD5.getMD5(imageURL)
                + imageURL.substring(imageURL.lastIndexOf("."));
        


        if (imageCache.containsKey(imageURL)) {// 在內存緩存中,則返回drawable對象
            SoftReference<Drawable> cache = imageCache.get(imageURL);
            Drawable drawable = cache.get();
            if (drawable != null) {
                System.out.println("softReference");
                return drawable;
            } else {
                System.out.print("had jvm ");
                imageCache.remove(imageURL);
                drawable = getFileImage(imageURL, strfilename);
                if (drawable != null)
                    return drawable;
            }
        } else {
            Drawable drawable = getFileImage(imageURL, strfilename);
            if (drawable != null)
                return drawable;
        }
        final Handler handler = new Handler() {
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(Message msg) {
                imageCallBack.imageLoad(imageURL, (Drawable) msg.obj);
            }
        };


        executor.execute(generateDownloadRunnable(imageURL, strfilename, handler));
        return null;
    }


    private Runnable generateDownloadRunnable(final String imageURL,
            final String strfilename, final Handler handler) {
        return new Runnable() {
            public void run() {
                File file = FileOperate.createFile(cachefile, strfilename);
                try {
                    URL url = new URL(imageURL);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream stream = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(stream);
                    Drawable drawable = new BitmapDrawable(bitmap);


                    imageCache.put(imageURL, new SoftReference<Drawable>(
                            drawable));


                    Message msg = handler.obtainMessage(0, drawable);
                    handler.sendMessage(msg);


                    FileOutputStream fos = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);


                    fos.close();
                    stream.close();
                    System.out.println("url");


                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }


            }
        };
    }


    private Drawable getFileImage(String imageURL, String strfilename) {
        File file = new File(cachefile, strfilename);
        if (file.exists()) {
            Drawable drawable = Drawable.createFromPath(file.toString());
            imageCache.put(imageURL, new SoftReference<Drawable>(drawable));
            System.out.println("come file");
            return drawable;
        }
        return null;
    }
}



public class FileOperate extends File {

    private static final long serialVersionUID = 6359476869554251131L;
    private final static String CACHE = "/Testimage06";
    
    public FileOperate(File dir, String name) {
        super(dir, name);
    }

    public static File isExistsFile() {
        File sdDir = null;
        File cachefile = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);//判斷sdcard是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//得到sdcard路徑
            cachefile = new File(sdDir,CACHE);
            if (!cachefile.exists()) {
                cachefile.mkdirs();
            }
        } else {
            System.out.println("can not find sdCard");
        }
        
        return cachefile;
    }

    public static File createFile(File path,String strfilename) {
        File file = new File(path,strfilename);
        try {
            file.createNewFile();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return file;
    }
}



public class MD5 {
    
    private static final String MD5 = "MD5";
    /**
     *
     * md5 創建MD5信息摘要
     * @param str 需要加密的字符串
     * @return 加密後的字符串
     * @throws NoSuchAlgorithmException

     */

    //半加密
    public static String getMD5(String str) {
        MessageDigest md5;
        byte[] m = null;
        try {
            md5 = MessageDigest.getInstance(MD5);//實現MD5算法的 MessageDigest 對象
            md5.update(str.getBytes());//使用str字節更新摘要
            m = md5.digest();//通過執行諸如填充之類的最終操作完成哈希計算。在調用此方法之後,摘要被重置
            
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i<m.length;i++){
            sb.append(m[i]);
        }
        return sb.toString();        
    }

//標準加密

public static String getMD5HexString(String content) {
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] md5Keys = digest.digest(content.getBytes("utf-8"));
String hexString = toHexString(md5Keys).toUpperCase();
return hexString;
}
catch (NoSuchAlgorithmException e)
{e.printStackTrace();}
catch (UnsupportedEncodingException e)
{e.printStackTrace();}return null;}
 
private static String toHexString(byte b[]) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String plainText = Integer.toHexString(0xff & b[i]);
if (plainText.length() < 2)
plainText = "0" + plainText;hexString.append(plainText);}
return hexString.toString();
}

}

AndroidManifest.xml

        <uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

public interface ImageCallBack {public void imageLoad(String strurl, Drawable drawable); }

public class Person {
    private String strPersonName;
    private int intPersonAge;
    private String strUrlImageAddress;
    
    public Person(String strPersonName, int intPersonAge,
            String strUrlImageAddress) {
        super();
        this.strPersonName = strPersonName;
        this.intPersonAge = intPersonAge;
        this.strUrlImageAddress = strUrlImageAddress;
    }
    
    public String getStrPersonName() {
        return strPersonName;
    }
    public void setStrPersonName(String strPersonName) {
        this.strPersonName = strPersonName;
    }
    public int getIntPersonAge() {
        return intPersonAge;
    }
    public void setIntPersonAge(int intPersonAge) {
        this.intPersonAge = intPersonAge;
    }
    public String getStrUrlImageAddress() {
        return strUrlImageAddress;
    }
    public void setStrUrlImageAddress(String strUrlImageAddress) {
        this.strUrlImageAddress = strUrlImageAddress;
    }
    
}


list_item01.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:descendantFocusability="blocksDescendants" >

    <ImageView
        android:id="@+id/ItemImage"
        android:layout_width="60dip"
        android:layout_height="80dip"
        android:layout_alignParentLeft="true"
        >
    </ImageView>

    <TextView
        android:id="@+id/ItemTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/ItemImage"
        android:singleLine="true"
         >
    </TextView>

    <TextView
        android:id="@+id/ItemText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/ItemTitle"
        android:layout_toRightOf="@+id/ItemImage"
        >
    </TextView>
    
    <Button
            android:id="@+id/ItemBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:layout_alignParentRight="true"
            android:text="@string/more"
        >
     </Button>

</RelativeLayout>

如有不能實現的可以聯繫我,對文檔如有什麼要求,希望提出來 ,交流交流。

源碼:http://download.csdn.net/detail/songconglai/4667087
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章