国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android App中實現(xiàn)圖片異步加載的實例分享

2019-12-12 06:33:49
字體:
供稿:網(wǎng)友

一、概述
一般大量圖片的加載,比如GridView實現(xiàn)手機的相冊功能,一般會用到LruCache,線程池,任務隊列等;那么異步消息處理可以用哪呢?
1、用于UI線程當Bitmap加載完成后更新ImageView
2、在圖片加載類初始化時,我們會在一個子線程中維護一個Loop實例,當然子線程中也就有了MessageQueue,Looper會一直在那loop停著等待消息的到達,當有消息到達時,從任務隊列按照隊列調(diào)度的方式(FIFO,LIFO等),取出一個任務放入線程池中進行處理。
簡易的一個流程:當需要加載一張圖片,首先把加載圖片加入任務隊列,然后使用loop線程(子線程)中的hander發(fā)送一個消息,提示有任務到達,loop()(子線程)中會接著取出一個任務,去加載圖片,當圖片加載完成,會使用UI線程的handler發(fā)送一個消息去更新UI界面。
說了這么多,大家估計也覺得云里來霧里去的,下面看實際的例子。

二、圖庫功能的實現(xiàn)
該程序首先掃描手機中所有包含圖片的文件夾,最終選擇圖片最多的文件夾,使用GridView顯示其中的圖片

1、布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:tools="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent" >   <GridView   android:id="@+id/id_gridView"   android:layout_width="match_parent"   android:layout_height="match_parent"   android:cacheColorHint="@android:color/transparent"   android:columnWidth="90dip"   android:gravity="center"   android:horizontalSpacing="20dip"   android:listSelector="@android:color/transparent"   android:numColumns="auto_fit"   android:stretchMode="columnWidth"   android:verticalSpacing="20dip" >  </GridView>  </RelativeLayout> 

布局文件相當簡單就一個GridView
2、MainActivity

package com.example.zhy_handler_imageloader;  import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import java.util.HashSet; import java.util.List;  import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.Toast;  public class MainActivity extends Activity {  private ProgressDialog mProgressDialog;  private ImageView mImageView;    /**   * 存儲文件夾中的圖片數(shù)量   */  private int mPicsSize;  /**   * 圖片數(shù)量最多的文件夾   */  private File mImgDir;  /**   * 所有的圖片   */  private List<String> mImgs;   private GridView mGirdView;  private ListAdapter mAdapter;  /**   * 臨時的輔助類,用于防止同一個文件夾的多次掃描   */  private HashSet<String> mDirPaths = new HashSet<String>();   private Handler mHandler = new Handler()  {   public void handleMessage(android.os.Message msg)   {    mProgressDialog.dismiss();    mImgs = Arrays.asList(mImgDir.list(new FilenameFilter()    {     @Override     public boolean accept(File dir, String filename)     {      if (filename.endsWith(".jpg"))       return true;      return false;     }    }));    /**     * 可以看到文件夾的路徑和圖片的路徑分開保存,極大的減少了內(nèi)存的消耗;     */    mAdapter = new MyAdapter(getApplicationContext(), mImgs,      mImgDir.getAbsolutePath());    mGirdView.setAdapter(mAdapter);   };  };   @Override  protected void onCreate(Bundle savedInstanceState)  {   super.onCreate(savedInstanceState);   setContentView(R.layout.activity_main);   mGirdView = (GridView) findViewById(R.id.id_gridView);   getImages();   }   /**   * 利用ContentProvider掃描手機中的圖片,此方法在運行在子線程中 完成圖片的掃描,最終獲得jpg最多的那個文件夾   */  private void getImages()  {   if (!Environment.getExternalStorageState().equals(     Environment.MEDIA_MOUNTED))   {    Toast.makeText(this, "暫無外部存儲", Toast.LENGTH_SHORT).show();    return;   }   // 顯示進度條   mProgressDialog = ProgressDialog.show(this, null, "正在加載...");    new Thread(new Runnable()   {     @Override    public void run()    {     Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;     ContentResolver mContentResolver = MainActivity.this       .getContentResolver();      // 只查詢jpeg和png的圖片     Cursor mCursor = mContentResolver.query(mImageUri, null,       MediaStore.Images.Media.MIME_TYPE + "=? or "         + MediaStore.Images.Media.MIME_TYPE + "=?",       new String[] { "image/jpeg", "image/png" },       MediaStore.Images.Media.DATE_MODIFIED);      while (mCursor.moveToNext())     {      // 獲取圖片的路徑      String path = mCursor.getString(mCursor        .getColumnIndex(MediaStore.Images.Media.DATA));      // 獲取該圖片的父路徑名      File parentFile = new File(path).getParentFile();      String dirPath = parentFile.getAbsolutePath();            //利用一個HashSet防止多次掃描同一個文件夾(不加這個判斷,圖片多起來還是相當恐怖的~~)      if(mDirPaths.contains(dirPath))      {       continue;      }      else      {       mDirPaths.add(dirPath);      }            int picSize = parentFile.list(new FilenameFilter()      {       @Override       public boolean accept(File dir, String filename)       {        if (filename.endsWith(".jpg"))         return true;        return false;       }      }).length;      if (picSize > mPicsSize)      {       mPicsSize = picSize;       mImgDir = parentFile;      }     }     mCursor.close();     //掃描完成,輔助的HashSet也就可以釋放內(nèi)存了     mDirPaths = null ;     // 通知Handler掃描圖片完成     mHandler.sendEmptyMessage(0x110);     }   }).start();   } } 

MainActivity也是比較簡單的,使用ContentProvider輔助,找到圖片最多的文件夾后,直接handler去隱藏ProgressDialog,然后初始化數(shù)據(jù),適配器等;
但是稍微注意一下:
(1)在掃描圖片時,使用了一個臨時的HashSet保存掃描過的文件夾,這樣可以有效的避免重復掃描。比如,我手機中有個文件夾下面有3000多張圖片,如果不判斷則會掃描這個文件夾3000多次,處理器時間以及內(nèi)存的消耗還是很可觀的。
(2)在適配器中,保存List<String>的時候,考慮只保存圖片的名稱,路徑單獨作為變量傳入。一般情況下,圖片的路徑比圖片名長很多,加入有3000張圖片,路徑長度30,圖片平均長度10,則List<String>保存完成路徑需要長度為:(30+10)*3000 = 120000 ; 而單獨存儲只需要:30+10*3000 = 30030 ; 圖片越多,節(jié)省的內(nèi)存越客觀;
總之,盡可能的去減少內(nèi)存的消耗,這些都是很容易做到的~

3、GridView的適配器

package com.example.zhy_handler_imageloader;  import java.util.List;  import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView;  import com.zhy.utils.ImageLoader;  public class MyAdapter extends BaseAdapter {   private Context mContext;  private List<String> mData;  private String mDirPath;  private LayoutInflater mInflater;  private ImageLoader mImageLoader;   public MyAdapter(Context context, List<String> mData, String dirPath)  {   this.mContext = context;   this.mData = mData;   this.mDirPath = dirPath;   mInflater = LayoutInflater.from(mContext);    mImageLoader = ImageLoader.getInstance();  }   @Override  public int getCount()  {   return mData.size();  }   @Override  public Object getItem(int position)  {   return mData.get(position);  }   @Override  public long getItemId(int position)  {   return position;  }   @Override  public View getView(int position, View convertView, final ViewGroup parent)  {   ViewHolder holder = null;   if (convertView == null)   {    holder = new ViewHolder();    convertView = mInflater.inflate(R.layout.grid_item, parent,      false);    holder.mImageView = (ImageView) convertView      .findViewById(R.id.id_item_image);    convertView.setTag(holder);   } else   {    holder = (ViewHolder) convertView.getTag();   }   holder.mImageView     .setImageResource(R.drawable.friends_sends_pictures_no);   //使用Imageloader去加載圖片   mImageLoader.loadImage(mDirPath + "/" + mData.get(position),     holder.mImageView);   return convertView;  }   private final class ViewHolder  {   ImageView mImageView;  }  } 

可以看到與傳統(tǒng)的適配器的寫法基本沒有什么不同之處,甚至在getView里面都沒有出現(xiàn)常見的回調(diào)(findViewByTag~用于防止圖片的錯位);僅僅多了一行代碼:

mImageLoader.loadImage(mDirPath + "/" + mData.get(position),holder.mImageView);

是不是用起來還是相當爽的,所有需要處理的細節(jié)都被封裝了。

4、ImageLoader
現(xiàn)在才到了關(guān)鍵的時刻,我們封裝的ImageLoader類,當然我們的異步消息處理機制也出現(xiàn)在其中。
首先是一個懶加載的單例

/**   * 單例獲得該實例對象   *   * @return   */  public static ImageLoader getInstance()  {    if (mInstance == null)   {    synchronized (ImageLoader.class)    {     if (mInstance == null)     {      mInstance = new ImageLoader(1, Type.LIFO);     }    }   }   return mInstance;  } 

沒啥說的,直接調(diào)用私有的構(gòu)造方法,可以看到,默認傳入了1(線程池中線程的數(shù)量),和LIFO(隊列的工作方式)

private ImageLoader(int threadCount, Type type)  {   init(threadCount, type);  }   private void init(int threadCount, Type type)  {   // loop thread   mPoolThread = new Thread()   {    @Override    public void run()    {     try     {      // 請求一個信號量      mSemaphore.acquire();     } catch (InterruptedException e)     {     }     Looper.prepare();      mPoolThreadHander = new Handler()     {      @Override      public void handleMessage(Message msg)      {       mThreadPool.execute(getTask());       try       {        mPoolSemaphore.acquire();       } catch (InterruptedException e)       {       }      }     };     // 釋放一個信號量     mSemaphore.release();     Looper.loop();    }   };   mPoolThread.start();    // 獲取應用程序最大可用內(nèi)存   int maxMemory = (int) Runtime.getRuntime().maxMemory();   int cacheSize = maxMemory / 8;   mLruCache = new LruCache<String, Bitmap>(cacheSize)   {    @Override    protected int sizeOf(String key, Bitmap value)    {     return value.getRowBytes() * value.getHeight();    };   };    mThreadPool = Executors.newFixedThreadPool(threadCount);   mPoolSemaphore = new Semaphore(threadCount);   mTasks = new LinkedList<Runnable>();   mType = type == null ? Type.LIFO : type;   } 

然后在私有構(gòu)造里面調(diào)用了我們的init方法,在這個方法的開始就創(chuàng)建了mPoolThread這個子線程,在這個子線程中我們執(zhí)行了Looper.prepare,初始化mPoolThreadHander,Looper.loop;如果看過上篇博客,一定知道,此時在這個子線程中維護了一個消息隊列,且這個子線程會進入一個無限讀取消息的循環(huán)中,而mPoolThreadHander這個handler發(fā)送的消息會直接發(fā)送至此線程中的消息隊列。然后看mPoolThreadHander中handleMessage的方法,直接調(diào)用了getTask方法取出一個任務,然后放入線程池去執(zhí)行。如果你比較細心,可能會發(fā)現(xiàn)里面還有一些信號量的操作的代碼 。 簡單說一下mSemaphore(信號數(shù)為1)的作用,由于mPoolThreadHander實在子線程初始化的,所以我在初始化前調(diào)用了mSemaphore.acquire去請求一個信號量,然后在初始化完成后釋放了此信號量,我為什么這么做呢?因為在主線程可能會立即使用到mPoolThreadHander,但是mPoolThreadHander是在子線程初始化的,雖然速度很快,但是我也不能百分百的保證,主線程使用時已經(jīng)初始化結(jié)束,為了避免空指針異常,所以我在主線程需要使用的時候,是這么調(diào)用的:

/**   * 添加一個任務   *   * @param runnable   */  private synchronized void addTask(Runnable runnable)  {   try   {    // 請求信號量,防止mPoolThreadHander為null    if (mPoolThreadHander == null)     mSemaphore.acquire();   } catch (InterruptedException e)   {   }   mTasks.add(runnable);   mPoolThreadHander.sendEmptyMessage(0x110);  } 

如果mPoolThreadHander沒有初始化完成,則會去acquire一個信號量,其實就是去等待mPoolThreadHander初始化完成。如果對此感興趣的,可以將關(guān)于mSemaphore的代碼注釋,然后在初始化mPoolThreadHander使用Thread.sleep去暫停1秒,就會發(fā)現(xiàn)這樣的錯誤。
初始化結(jié)束,就會在getView中調(diào)用

mImageLoader.loadImage(mDirPath + "/" + mData.get(position),holder.mImageView);

方法了,所以我們?nèi)タ磍oadImage方法吧

/**   * 加載圖片   *   * @param path   * @param imageView   */  public void loadImage(final String path, final ImageView imageView)  {   // set tag   imageView.setTag(path);   // UI線程   if (mHandler == null)   {    mHandler = new Handler()    {     @Override     public void handleMessage(Message msg)     {      ImgBeanHolder holder = (ImgBeanHolder) msg.obj;      ImageView imageView = holder.imageView;      Bitmap bm = holder.bitmap;      String path = holder.path;      if (imageView.getTag().toString().equals(path))      {       imageView.setImageBitmap(bm);      }     }    };   }    Bitmap bm = getBitmapFromLruCache(path);   if (bm != null)   {    ImgBeanHolder holder = new ImgBeanHolder();    holder.bitmap = bm;    holder.imageView = imageView;    holder.path = path;    Message message = Message.obtain();    message.obj = holder;    mHandler.sendMessage(message);   } else   {    addTask(new Runnable()    {     @Override     public void run()     {       ImageSize imageSize = getImageViewWidth(imageView);       int reqWidth = imageSize.width;      int reqHeight = imageSize.height;       Bitmap bm = decodeSampledBitmapFromResource(path, reqWidth,        reqHeight);      addBitmapToLruCache(path, bm);      ImgBeanHolder holder = new ImgBeanHolder();      holder.bitmap = getBitmapFromLruCache(path);      holder.imageView = imageView;      holder.path = path;      Message message = Message.obtain();      message.obj = holder;      // Log.e("TAG", "mHandler.sendMessage(message);");      mHandler.sendMessage(message);      mPoolSemaphore.release();     }    });   }   } 

這段代碼比較長,當然也是比較核心的代碼了
10-29行:首先將傳入imageView設置了path,然在初始化了一個mHandler用于設置imageView的bitmap,注意此時在UI線程,也就是這個mHandler發(fā)出的消息,會在UI線程中調(diào)用。可以看到在handleMessage中,我們從消息中取出ImageView,bitmap,path;然后將path與imageView的tag進行比較,防止圖片的錯位,最后設置bitmap;
31行:我們首先去從LruCache中去查找是否已經(jīng)緩存了此圖片
32-40:如果找到了,則直接使用mHandler去發(fā)送消息,這里使用了一個ImgBeanHolder去封裝了ImageView,Bitmap,Path這三個對象。然后更新執(zhí)行handleMessage代碼去更新UI
43-66行:如果沒有存在緩存中,則創(chuàng)建一個Runnable對象作為任務,去執(zhí)行addTask方法加入任務隊列
49行:getImageViewWidth根據(jù)ImageView獲取適當?shù)膱D片的尺寸,用于后面的壓縮圖片,代碼按順序貼下下面
54行:會根據(jù)計算的需要的寬和高,對圖片進行壓縮。代碼按順序貼下下面
56行:將壓縮后的圖片放入緩存
58-64行,創(chuàng)建消息,使用mHandler進行發(fā)送,更新UI

/**   * 根據(jù)ImageView獲得適當?shù)膲嚎s的寬和高   *   * @param imageView   * @return   */  private ImageSize getImageViewWidth(ImageView imageView)  {   ImageSize imageSize = new ImageSize();   final DisplayMetrics displayMetrics = imageView.getContext()     .getResources().getDisplayMetrics();   final LayoutParams params = imageView.getLayoutParams();    int width = params.width == LayoutParams.WRAP_CONTENT ? 0 : imageView     .getWidth(); // Get actual image width   if (width <= 0)    width = params.width; // Get layout width parameter   if (width <= 0)    width = getImageViewFieldValue(imageView, "mMaxWidth"); // Check                  // maxWidth                  // parameter   if (width <= 0)    width = displayMetrics.widthPixels;   int height = params.height == LayoutParams.WRAP_CONTENT ? 0 : imageView     .getHeight(); // Get actual image height   if (height <= 0)    height = params.height; // Get layout height parameter   if (height <= 0)    height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check                   // maxHeight                   // parameter   if (height <= 0)    height = displayMetrics.heightPixels;   imageSize.width = width;   imageSize.height = height;   return imageSize;   } /**   * 根據(jù)計算的inSampleSize,得到壓縮后圖片   *   * @param pathName   * @param reqWidth   * @param reqHeight   * @return   */  private Bitmap decodeSampledBitmapFromResource(String pathName,    int reqWidth, int reqHeight)  {   // 第一次解析將inJustDecodeBounds設置為true,來獲取圖片大小   final BitmapFactory.Options options = new BitmapFactory.Options();   options.inJustDecodeBounds = true;   BitmapFactory.decodeFile(pathName, options);   // 調(diào)用上面定義的方法計算inSampleSize值   options.inSampleSize = calculateInSampleSize(options, reqWidth,     reqHeight);   // 使用獲取到的inSampleSize值再次解析圖片   options.inJustDecodeBounds = false;   Bitmap bitmap = BitmapFactory.decodeFile(pathName, options);    return bitmap;  } 

接下來看AddTask的代碼:

/**   * 添加一個任務   *   * @param runnable   */  private synchronized void addTask(Runnable runnable)  {   try   {    // 請求信號量,防止mPoolThreadHander為null    if (mPoolThreadHander == null)     mSemaphore.acquire();   } catch (InterruptedException e)   {   }   mTasks.add(runnable);   mPoolThreadHander.sendEmptyMessage(0x110);  } 

可以看到,簡單把任務放入任務隊列,然后使用mPoolThreadHander發(fā)送一個消息到后臺的loop中,后臺的loop會取出消息執(zhí)行:

mThreadPool.execute(getTask());

execute執(zhí)行的就是上面分析的Runnable中的run方法了。
注意一下:上述代碼中還會看到mPoolSemaphore這個信號量的身影,說下用處;因為調(diào)用addTask之后,會直接去從任務隊列取出一個任務,放入線程池,由于線程池內(nèi)部其實也維持著一個隊列,那么”從任務隊列取出一個任務”這個動作會瞬間完成,直接加入線程池維護的隊列中;這樣會造成比如用戶設置了調(diào)度隊列為LIFO,但是由于”從任務隊列取出一個任務”這個動作會瞬間完成,隊列中始終維持在空隊列的狀態(tài),所以讓用戶感覺LIFO根本沒有效果;所以我按照用戶設置線程池工作線程的數(shù)量設置了一個信號量,這樣在保證任務執(zhí)行完后,才會從任務隊列去取任務,使得LIFO有著很好的效果;有興趣的可以注釋了所有的mPoolSemaphore代碼,測試下就明白了。
到此代碼基本介紹完畢。細節(jié)還是很多的,后面會附上源碼,有興趣的研究下代碼,沒有興趣的,可以運行下代碼,如果感覺流暢性不錯,體驗不錯,可以作為工具類直接使用,使用也就getView里面一行代碼。

貼一下效果圖,我手機最多的文件夾大概3000張圖片,加載速度還是相當相當流暢的:

真機錄的,有點丟幀,注意看效果圖,中間我瘋狂拖動滾動條,但是圖片基本還是瞬間顯示的。
說一下,F(xiàn)IFO如果設置為這個模式,在控件中不做處理的話,用戶拉的比較慢效果還是不錯的,但是用戶手機如果有個幾千張,瞬間拉到最后,最后一屏圖片的顯示可能需要喝杯茶了~當然了,大家可以在控件中做處理,要么,拖動的時候不去加載圖片,停在來再加載。或者,當手機抬起,給了一個很大的加速度,屏幕還是很快的滑動時停止加載,停下時加載圖片。
LIFO這個模式可能用戶體驗會好很多,不管用戶拉多塊,最終停下來的那一屏圖片都會瞬間顯示~
最后掰一掰使用異步消息處理機制作為背后的子線程的好處,其實直接用一個子線程也可以實現(xiàn),但是,這個子線程run中可能需要while(true)然后每隔200毫秒甚至更短的時間去查詢?nèi)蝿贞犃惺欠裼腥蝿眨瑳]有則Thread.sleep,然后再去查詢;這樣如果長時間沒有去添加任務,這個線程依然會不斷的去查詢;
而異步消息機制,只有在發(fā)送消息時才會去執(zhí)行,當然更準確;當長時間沒有任務到達時,也不會去查詢,會一直阻塞在這;還有一點,這個機制Android內(nèi)部實現(xiàn)的,怎么也比我們搞個Thread穩(wěn)定性、效率高吧~

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 嘉禾县| 乐东| 临汾市| 萨嘎县| 呼玛县| 凉城县| 东乌| 府谷县| 监利县| 宽甸| 和平区| 呼玛县| 威宁| 临夏市| 甘谷县| 昌图县| 沙田区| 祁东县| 宣化县| 洪雅县| 依兰县| 报价| 绥阳县| 榆中县| 绥德县| 潼关县| 广西| 青海省| 天全县| 垫江县| 桂林市| 莱阳市| 修文县| 博爱县| 五大连池市| 买车| 延寿县| 武乡县| 勃利县| 松江区| 竹北市|