序文
実際、私は1週間のエントリーの後、兄弟を開発するために2人の兄弟に従うことができます。最近、私は今日、Androidクライアントの画像が非同期であるというクラスを完成させたばかりです(実際には、オンラインのオープンソースの実装を参照してください)
原理
ListViewまたはGridViewに写真をロードする原則は、基本的に同じです。
メモリキャッシュから取得し、ファイルキャッシュから次のステップを取得できない場合は、メモリキャッシュを取得できない場合は、
フローチャートは次のとおりです。
同時に、スレッドの数に注意してください。一般に、ListViewに写真をロードすると、誰もが新しいスレッドを開きますが、すぐにスライドするとOOMを引き起こすのは簡単であるため、スレッドの数を制御する必要があります。スレッドプールを介してスレッドの数を制御できます。
スレッドプールを確立する方法は次のとおりです。
executorservice executorservice = executors.netfixedthreadpool(5);
ファイルキャッシュクラス
Import java.io.file.content.context; os.environment.getExternalStoragestate()等しい(android.os.environment.media_moundted){cachedir = new file textalstoragedirectory()、dir_name);} else {cachedir = context.getcachedir();} ){cachedir.mkders();}} public file getFile(string url){// urlのハッシュコード文字列filename = string.valueof(url.hashcode()); ;} public void clear(){files.listfiles();メモリキャッシュクラス
ソフトリファレンス、Map <String、softreference <bitmap >>キャッシュは、単純に実装されています
Import Java.util.util.linkedhasmap;コレクション同期ref.get();} public void put(string id、bitmap bitmap){cache.put(id、new softreference <bit map>(bitmap);} public void clear(){cache.clear();}}}}画像読み込みクラス
java.io.filenotfoundection。 util.util.util.weakhap BitMapFactory;画像キャッシュ * / MemoryCache(); SynchronizedMap(新しいweakhashmap、string、string>()); {filecache = new filecache(context);メモリキャッシュからの画像ImageView.setImageBitmap(bitmap);} else {//ファイルキャッシュまたはネットワークqueephoto(url、imagev iew);}} private void queephoto(string url、imageView imageView){athotoload ethotoload = new whototoload(url 、ImageView) {networe bitmap = null = new url(url); (true)= conn.getInputStream(f); {if(exstance of outofmemoryerror){clearcache();} private void copystream(outputstream os){int buffer_size = 1024; .read(bytes、0、buffer_size); if(count == -1){break;} os.wri te(te bytes、0、count);}} f){// todo:画像サイズFileInputStreamを圧縮するbitmap = bitmapfactory.decodeStream(fileinputStream)(filenotfoundexception e){return null;}} {MemoryCache.Clear(); url、imageView ImageView){this.url = url;} / ** * @author zhengyi.wzy * * / class fotodeer runnable {photoload phototoload; ){this.phototoload = phototoload;} private boolean imageViewreused(phototoload photoload){string tag = imageViews.get(Phototoload.im.im.im.im.im.im.im.im ageview); ||!tag.equals(phototoload.url)){return true;} @override public void run(){// abort current thread im age view reuse BitMap Bitmap = getBitMap(PhotoToload.url); Bitmapdisplayer (Bitmap, PhotoToload); Handler.post (BD);} Class Bitmapdisplayer IMPLEMENTS Runnable {BI TMAP BITMAP; PhotoToload PhotoToload; Public Bitmapdisplayer (bitmap bitmap, Photoload PhotoLoad) {this.bitmap = bitmap; this. PhotoLoad = PHOTOTOLOAD;} @Override public void run(){if(imageViewReused(photoToload)){return;} if(bitmap!= null)oad.imageview.setimageBitmap(bitmap);} els {phototoload.imageView.setimageresource(default);}}}}}} }}通話方法
ImageLoader imageLoader = new ImageLoader(Context);