歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android異步加載圖像(含線程池,緩存方法)

Android異步加載圖像(含線程池,緩存方法)

日期:2017/3/1 10:21:05   编辑:Linux編程

研究了Android從網絡上異步加載圖像:

(1)由於android UI更新支持單一線程原則,所以從網絡上取數據並更新到界面上,為了不阻塞主線程首先可能會想到以下方法。

在主線程中new 一個Handler對象,加載圖像方法如下所示

  1. private void loadImage(final String url, final int id) {
  2. handler.post(new Runnable() {
  3. public void run() {
  4. Drawable drawable = null;
  5. try {
  6. drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
  7. } catch (IOException e) {
  8. }
  9. ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
  10. }
  11. });
  12. }

上面這個方法缺點很顯然,經測試,如果要加載多個圖片,這並不能實現異步加載,而是等到所有的圖片都加載完才一起顯示,因為它們都運行在一個線程中。

然後,我們可以簡單改進下,將Handler+Runnable模式改為Handler+Thread+Message模式不就能實現同時開啟多個線程嗎?

(2)在主線程中new 一個Handler對象,代碼如下:

  1. final Handler handler2=new Handler(){
  2. @Override
  3. public void handleMessage(Message msg) {
  4. ((ImageView) LazyLoadImageActivity.this.findViewById(msg.arg1)).setImageDrawable((Drawable)msg.obj);
  5. }
  6. };

對應加載圖像代碼如下:對應加載圖像代碼如下:對應加載圖像代碼如下:

  1. // 引入線程池來管理多線程
  2. private void loadImage3(final String url, final int id) {
  3. executorService.submit(new Runnable() {
  4. public void run() {
  5. try {
  6. final Drawable drawable = Drawable.createFromStream(new URL(url).openStream(), "image.png");
  7. handler.post(new Runnable() {
  8. public void run() {
  9. ((ImageView) LazyLoadImageActivity.this.findViewById(id)).setImageDrawable(drawable);
  10. }
  11. });
  12. } catch (Exception e) {
  13. throw new RuntimeException(e);
  14. }
  15. }
  16. });
  17. }

(4)為了更方便使用我們可以將異步加載圖像方法封裝一個類,對外界只暴露一個方法即可,考慮到效率問題我們可以引入內存緩存機制,做法是

建立一個HashMap,其鍵(key)為加載圖像url,其值(value)是圖像對象Drawable。先看一下我們封裝的類

  1. public class AsyncImageLoader3 {
  2. //為了加快速度,在內存中開啟緩存(主要應用於重復圖片較多時,或者同一個圖片要多次被訪問,比如在ListView時來回滾動)
  3. public Map<String, SoftReference<Drawable>> imageCache = new HashMap<String, SoftReference<Drawable>>();
  4. private ExecutorService executorService = Executors.newFixedThreadPool(5); //固定五個線程來執行任務
  5. private final Handler handler=new Handler();
  6. /**
  7. *
  8. * @param imageUrl 圖像url地址
  9. * @param callback 回調接口
  10. * @return 返回內存中緩存的圖像,第一次加載返回null
  11. */
  12. public Drawable loadDrawable(final String imageUrl, final ImageCallback callback) {
  13. //如果緩存過就從緩存中取出數據
  14. if (imageCache.containsKey(imageUrl)) {
  15. SoftReference<Drawable> softReference = imageCache.get(imageUrl);
  16. if (softReference.get() != null) {
  17. return softReference.get();
  18. }
  19. }
  20. //緩存中沒有圖像,則從網絡上取出數據,並將取出的數據緩存到內存中
  21. executorService.submit(new Runnable() {
  22. public void run() {
  23. try {
  24. final Drawable drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
  25. imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
  26. handler.post(new Runnable() {
  27. public void run() {
  28. callback.imageLoaded(drawable);
  29. }
  30. });
  31. } catch (Exception e) {
  32. throw new RuntimeException(e);
  33. }
  34. }
  35. });
  36. return null;
  37. }
  38. //從網絡上取數據方法
  39. protected Drawable loadImageFromUrl(String imageUrl) {
  40. try {
  41. return Drawable.createFromStream(new URL(imageUrl).openStream(), "image.png");
  42. } catch (Exception e) {
  43. throw new RuntimeException(e);
  44. }
  45. }
  46. //對外界開放的回調接口
  47. public interface ImageCallback {
  48. //注意 此方法是用來設置目標對象的圖像資源
  49. public void imageLoaded(Drawable imageDrawable);
  50. }
  51. }

這樣封裝好後使用起來就方便多了。在主線程中首先要引入AsyncImageLoader3 對象,然後直接調用其loadDrawable方法即可,需要注意的是ImageCallback接口的imageLoaded方法是唯一可以把加載的圖像設置到目標ImageView或其相關的組件上。

Copyright © Linux教程網 All Rights Reserved