0

如何優化我的代碼以加載圖像快速閃爍?我的意思是在快速上下滾動後,需要幾秒或更長時間才能將圖像加載到我的ListViewImageView中。這裏是我的適配器我的示例代碼:使用AsyncTask加載ListView有點慢圖像

public void bindView(View view, Context context, Cursor cursor) { 
     String title = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)); 
     String album_id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)); 
     ImageView iv = (ImageView)view.findViewById(R.id.imgIcon); 
     TextView text = (TextView)view.findViewById(R.id.txtTitle); 
     text.setText(title); 
     Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart"); 
     Uri uri = ContentUris.withAppendedId(sArtworkUri, Integer.valueOf(album_id)); 
     iv.setTag(uri); 
     iv.setImageResource(R.drawable.background_holo_dark); 
     new MyImageLoader(context,view,iv,uri).execute(uri); 

    } 

private class MyImageLoader extends AsyncTask<Uri, Void, Bitmap>{ 
     Context context; 
     View v; 
     ImageView iv; 
     Uri u; 

     MyImageLoader(Context context,View v,ImageView iv,Uri u){ 
      this.context = context; 
      this.v = v; 
      this.iv = iv; 
      this.u = u; 
     } 
     protected synchronized Bitmap doInBackground(Uri... param) { 
      ContentResolver res = context.getContentResolver(); 
      InputStream in = null; 
      try { 
       in = res.openInputStream(param[0]); 
      } 
      catch (FileNotFoundException e) { 

       e.printStackTrace(); 
      } 
      Bitmap artwork = BitmapFactory.decodeStream(in); 
      return artwork; 
     } 
     protected void onPostExecute(Bitmap bmp){ 
      if(bmp!=null) 
      { ImageView iv = (ImageView)v.findViewById(R.id.imgIcon); 
       if(iv.getTag().toString().equals(u.toString())) 
        iv.setImageBitmap(bmp); 
        //iv.setImageBitmap(Bitmap.createScaledBitmap(bmp, 100, 100, false)); 
      } 
     } 
    } 

回答

1

這裏有兩種東西,我能想到的:

  1. 在ICS開始的AsyncTask是singlethread的事情,這意味着,如果你開除10 AsyncTasks,它會完成第一個,然後到第二個,然後是第三個,在繼續之前總是等待其他人完成。您可以使用它的.executeOnExecutor方法來運行與更多線程並行的任務。

  2. 使用LruCache爲圖像執行RAM緩存。這究竟video from Google IO 2012說明如何使一個LruCache(我總是建議人們觀看了整個視頻,因爲有很多很酷的技巧的)

+0

'1.'我不能做我自己的目標是GB。 '2.'我會試試這個並且回覆你。 '3.'有沒有我可以做的任何優化讓它更快?我的意思是在現有的代碼中。而不是緩存。我知道的緩存會讓它更快。 '4.'我可以使用HashMap而不是LRU緩存來使東西更容易嗎? – h4ck3d 2013-02-24 17:59:39

+1

1. http://android-developers.blogspot.co.uk/2010/07/how-to-have-your-cupcake-and-eat-it-too.html 2.好的3.不是我能看到的無需自己構建並進行更密切的調試。 4.不需要使用LruCache。一個HashMap最終會使您的應用程序崩潰,並出現OutOfMemory錯誤。但請相信我,LruCache非常簡單,只需在幻燈片上看到的那幾行就可以在4:30 – Budius 2013-02-24 18:14:38

+0

LRU完成這項工作。 – h4ck3d 2013-02-25 22:22:04