当前位置: 移动技术网 > IT编程>移动开发>Android > 一起动手编写Android图片加载框架

一起动手编写Android图片加载框架

2019年07月24日  | 移动技术网IT编程  | 我要评论

曼联妖王女友晒美照 不惧走光,人猿泰山成人,圣斗士奇迹之海

开发一个简洁而实用的android图片加载缓存框架,并在内存占用与加载图片所需时间这两个方面与主流图片加载框架之一universal image loader做出比较,来帮助我们量化这个框架的性能。通过开发这个框架,我们可以进一步深入了解android中的bitmap操作、lrucache、lrudiskcache,让我们以后与bitmap打交道能够更加得心应手。若对bitmap的大小计算及insamplesize计算还不太熟悉,请参考这里:高效加载bitmap。由于个人水平有限,叙述中必然存在不准确或是不清晰的地方,希望大家能够指出,谢谢大家。

一、图片加载框架需求描述

    在着手进行实际开发工作之前,我们先来明确以下我们的需求。通常来说,一个实用的图片加载框架应该具备以下2个功能:

图片的加载:包括从不同来源(网络、文件系统、内存等),支持同步及异步方式,支持对图片的压缩等等;
图片的缓存:包括内存缓存和磁盘缓存。
    下面我们来具体描述下这些需求。

1. 图片的加载

(1)同步加载与异步加载
我们先来简单的复习下同步与异步的概念:

同步:发出了一个“调用”后,需要等到该调用返回才能继续执行;
异步:发出了一个“调用”后,无需等待该调用返回就能继续执行。
    同步加载就是我们发出加载图片这个调用后,直到完成加载我们才继续干别的活,否则就一直等着;异步加载也就是发出加载图片这个调用后我们可以直接去干别的活。

(2)从不同的来源加载
    我们的应用有时候需要从网络上加载图片,有时候需要从磁盘加载,有时候又希望从内存中直接获取。因此一个合格的图片加载框架应该支持从不同的来源来加载一个图片。对于网络上的图片,我们可以使用httpurlconnection来下载并解析;对于磁盘中的图片,我们可以使用bitmapfactory的decodefile方法;对于内存中的bitmap,我们直接就可以获取。

(3)图片的压缩
    关于对图片的压缩,主要的工作是计算出insamplesize,剩下的细节在下面实现部分我们会介绍。 

2. 图片的缓存

    缓存功能对于一个图片加载框架来说是十分必要的,因为从网络上加载图片既耗时耗电又费流量。通常我们希望把已经加载过的图片缓存在内存或磁盘中,这样当我们再次需要加载相同的图片时可以直接从内存缓存或磁盘缓存中获取。

(1)内存缓存
    访问内存的速度要比访问磁盘快得多,因此我们倾向于把更加常用的图片直接缓存在内存中,这样加载速度更快,内存缓存的不足在于由于内存空间有限,能够缓存的图片也比较少。我们可以选择使用sdk提供的lrucache类来实现内存缓存,这个类使用了lru算法来管理缓存对象,lru算法即least recently used(最近最少使用),它的主要思想是当缓存空间已满时,移除最近最少使用的缓存对象。关于lrucache类的具体使用我们下面会进行详细介绍。

(2)磁盘缓存
    磁盘缓存的优势在于能够缓存的图片数量比较多,不足就是磁盘io的速度比较慢。磁盘缓存我们可以用disklrucache来实现,这个类不属于android sdk,文末给出的本文示例代码的地址,其中包含了disklrucache。

    dislrucache同样使用了lru算法来管理缓存,关于它的具体使用我们会在后文进行介绍。 

二、缓存类使用介绍
1. lrucache的使用

    首先我们来看一下lrucache类的定义:

public class lrucache<k, v> {
  private final linkedhashmap<k, v> map;

  ...
  
  public lrucache(int maxsize) {
    if (maxsize <= 0) {
      throw new illegalargumentexception("maxsize <= 0");
    }
    this.maxsize = maxsize;
    this.map = new linkedhashmap<k, v>(0, 0.75f, true);
  }
  ...
}

    由以上代码我们可以知道,lrucache是个泛型类,它的内部使用一个linkedhashmap来管理缓存对象。

(1)初始化lrucache
初始化lrucache的惯用代码如下所示:

//获取当前进程的可用内存(单位kb)
int maxmemory = (int) (runtime.getruntime().maxmemory() /1024);
int memorycachesize = maxmemory / 8;
mmemorycache = new lrucache<string, bitmap>(memorycachesize) {
  @override
  protected int sizeof(string key, bitmap bitmap) {
    return bitmap.getbytecount() / 1024;
  }
};  

在以上代码中,我们创建了一个lrucache实例,并指定它的maxsize为当前进程可用内存的1/8。我们使用string作为key,value自然是bitmap。第6行到第8行我们重写了sizeof方法,这个方法被lrucache用来计算一个缓存对象的大小。我们使用了getbytecount方法返回bitmap对象以字节为单位的方法,又除以了1024,转换为kb为单位的大小,以达到与cachesize的单位统一。

(2)获取缓存对象
   lrucache类通过get方法来获取缓存对象,get方法的源码如下:

public final v get(k key) {
    if (key == null) {
      throw new nullpointerexception("key == null");
    }

    v mapvalue;
    synchronized (this) {
      mapvalue = map.get(key);
      if (mapvalue != null) {
        hitcount++;
        return mapvalue;
      }
      misscount++;
    }

    /*
     * attempt to create a value. this may take a long time, and the map
     * may be different when create() returns. if a conflicting value was
     * added to the map while create() was working, we leave that value in
     * the map and release the created value.
     */

    v createdvalue = create(key);
    if (createdvalue == null) {
      return null;
    }

    synchronized (this) {
      createcount++;
      mapvalue = map.put(key, createdvalue);

      if (mapvalue != null) {
        // there was a conflict so undo that last put
        map.put(key, mapvalue);
      } else {
        size += safesizeof(key, createdvalue);
      }
    }

    if (mapvalue != null) {
      entryremoved(false, key, createdvalue, mapvalue);
      return mapvalue;
    } else {
      trimtosize(maxsize);
      return createdvalue;
    }
  }

    通过以上代码我们了解到,首先会尝试根据key获取相应value(第8行),若不存在则会新建一个key-value对,并将它放入到linkedhashmap中。从get方法的实现我们可以看到,它用synchronized关键字作了同步,因此这个方法是线程安全的。实际上,lrucache类对所有可能涉及并发数据访问的方法都作了同步。

(3)添加缓存对象
    在添加缓存对象之前,我们先得确定用什么作为被缓存的bitmap对象的key,一种很直接的做法便是使用bitmap的url作为key,然而由于url中存在一些特殊字符,所以可能会产生一些问题。基于以上原因,我们可以考虑使用url的md5值作为key,这能够很好的保证不同的url具有不同的key,而且相同的url得到的key相同。我们自定义一个getkeyfromurl方法来通过uri获取key,该方法的代码如下:

  private string getkeyfromurl(string url) {
    string key;
    try {
      messagedigest messagedigest = messagedigest.getinstance("md5");
      messagedigest.update(url.getbytes());
      byte[] m = messagedigest.digest();
      return getstring(m);
    } catch (nosuchalgorithmexception e) {
      key = string.valueof(url.hashcode());
    }
    return key;
  }
  private static string getstring(byte[] b){
    stringbuffer sb = new stringbuffer();
    for(int i = 0; i < b.length; i ++){
      sb.append(b[i]);
    }
    return sb.tostring();
  }

 

    得到了key后,我们可以使用put方法向lrucache内部的linkedhashmap中添加缓存对象,这个方法的源码如下:

public final v put(k key, v value) {
    if (key == null || value == null) {
      throw new nullpointerexception("key == null || value == null");
    }

    v previous;
    synchronized (this) {
      putcount++;
      size += safesizeof(key, value);
      previous = map.put(key, value);
      if (previous != null) {
        size -= safesizeof(key, previous);
      }
    }

    if (previous != null) {
      entryremoved(false, key, previous, value);
    }

    trimtosize(maxsize);
    return previous;
}

    从以上代码我们可以看到这个方法确实也作了同步,它将新的key-value对放入linkedhashmap后会返回相应key原来对应的value。 

(4)删除缓存对象
    我们可以通过remove方法来删除缓存对象,这个方法的源码如下:

public final v remove(k key) {
    if (key == null) {
      throw new nullpointerexception("key == null");
    }

    v previous;
    synchronized (this) {
      previous = map.remove(key);
      if (previous != null) {
        size -= safesizeof(key, previous);
      }
    }

    if (previous != null) {
      entryremoved(false, key, previous, null);
    }

    return previous;
}

    这个方法会从linkedhashmap中移除指定key对应的value并返回这个value,我们可以看到它的内部还调用了entryremoved方法,如果有需要的话,我们可以重写entryremoved方法来做一些资源回收的工作。   

 2. disklrucache的使用

(1)初始化disklrucache
    通过查看disklrucache的源码我们可以发现,disklrucache就存在如下一个私有构造方法:

private disklrucache(file directory, int appversion, int valuecount, long maxsize) {
    this.directory = directory;
    this.appversion = appversion;
    this.journalfile = new file(directory, journal_file);
    this.journalfiletmp = new file(directory, journal_file_tmp);
    this.valuecount = valuecount;
    this.maxsize = maxsize;
}
 

    因此我们不能直接调用构造方法来创建disklrucache的实例。实际上disklrucache为我们提供了open静态方法来创建一个disklrucache实例,我们来看一下这个方法的实现:

public static disklrucache open(file directory, int appversion, int valuecount, long maxsize)
      throws ioexception {
    if (maxsize <= 0) {
      throw new illegalargumentexception("maxsize <= 0");
    }
    if (valuecount <= 0) {
      throw new illegalargumentexception("valuecount <= 0");
    }
 
    // prefer to pick up where we left off
    disklrucache cache = new disklrucache(directory, appversion, valuecount, maxsize);
    if (cache.journalfile.exists()) {
      try {
        cache.readjournal();
        cache.processjournal();
        cache.journalwriter = new bufferedwriter(new filewriter(cache.journalfile, true),
            io_buffer_size);
        return cache;
      } catch (ioexception journaliscorrupt) {
//        system.logw("disklrucache " + directory + " is corrupt: "
//            + journaliscorrupt.getmessage() + ", removing");
        cache.delete();
      }
    }
 
    // create a new empty cache
    directory.mkdirs();
    cache = new disklrucache(directory, appversion, valuecount, maxsize);
    cache.rebuildjournal();
    return cache;
}

     从以上代码中我们可以看到,open方法内部调用了disklrucache的构造方法,并传入了我们传入open方法的4个参数,这4个参数的含义分别如下:

directory:代表缓存文件在文件系统的存储路径;
appversion:代表应用版本号,通常设为1即可;
valuecount:代表linkedhashmap中每个节点上的缓存对象数目,通常设为1即可;
maxsize:代表了缓存的总大小,若缓存对象的总大小超过了maxsize,disklrucache会自动删去最近最少使用的一些缓存对象。
    以下代码展示了初始化disklrucache的惯用代码:

file diskcachedir= getappcachedir(mcontext, "images");
if (!diskcachedir.exists()) {
  diskcachedir.mkdirs();
}
mdisklrucache = disklrucache.open(diskcachedir, 1, 1, disk_cache_size); 

    以上代码中的getappcachedir是我们自定义的用来获取磁盘缓存目录的方法,它的定义如下:

public static file getappcachedir(context context, string dirname) {
  string cachedirstring;
  if (environment.media_mounted.equals(environment.getexternalstoragestate())) {
    cachedirstring = context.getexternalcachedir().getpath();
  } else {
    cachedirstring = context.getcachedir().getpath();
  }
  return new file(cachedirstring + file.separator + dirname);
}

接下来我们介绍如何添加、获取和删除缓存对象。 

(2)添加缓存对象
    先通过以上介绍的getkeyfromurl获取bitmap对象对应的key,接下来我们就可以把这个bitmap存入磁盘缓存中了。我们通过editor来向disklrucache添加缓存对象。首先我们要通过edit方法获取一个editor对象:

string key = getkeyfromurl(url);
disklrucache.editor editor = mdisklrucache.edit(key); 

获取到editor对象后,通过调用editor对象的newoutputstream我们就可以获取key对应的bitmap的输出流,需要注意的是,若我们想通过edit方法获取的那个缓存对象正在被“编辑”,那么edit方法会返回null。相关的代码如下:

if (editor != null) {
  outputstream outputstream = editor.newoutputstream(0); //参数为索引,由于我们创建时指定一个节点只有一个缓存对象,所以传入0即可
}

    获取了输出流后,我们就可以向这个输出流中写入图片数据,成功写入后调用commit方法即可,若写入失败则调用abort方法进行回退。相关的代码如下:

//getstream为我们自定义的方法,它通过url获取输入流并写入outputstream,具体实现后文会给出
if (getstreamfromurl(url, outputstream)) {
  editor.commit();
} else {
  //返回false表示写入outputstream未成功,因此调用abort方法回退整个操作
  editor.abort();
}
mdisklrucache.flush(); //将内存中的操作记录同步到日志文件中

    下面我们来看一下getstream方法的实现,这个方法实现很直接简单,就是创建一个httpurlconnection,然后获取inputstream再写入outputstream,为了提高效率,使用了包装流。该方法的代码如下:

public boolean getstreamfromurl(string urlstring, outputstream outputstream) {
  httpurlconnection urlconnection = null;
  bufferedinputstream bis = null;
  bufferedoutputstream bos = null;
  
  try {
    final url url = new url(urlstring);
    urlconnection = (httpurlconnection) url.openconnection();
    bis = new bufferedinputstream(urlconnection.getinputstream(), buf_size);
    
    int byteread;
    while ((byteread = bis.read()) != -1) {
      bos.write(byteread);
    }
    return true;
  }catch (ioexception e) {
    e.printstacktrace();
  } finally {
    if (urlconnection != null) {
      urlconnection.disconnect();
    }
    //httputils为一个自定义工具类
    httputils.close(bis);
    httputils.close(bos);
  }
  return false;
}

     经过以上的步骤,我们已经成功地将图片写入了文件系统。 

(3)获取缓存对象
    我们使用disklrucache的get方法从中获取缓存对象,这个方法的大致源码如下:

public synchronized snapshot get(string key) throws ioexception {
    checknotclosed();
    validatekey(key);
    entry entry = lruentries.get(key);
    if (entry == null) {
      return null;
    }
 
    if (!entry.readable) {
      return null;
    }
 
    /*
     * open all streams eagerly to guarantee that we see a single published
     * snapshot. if we opened streams lazily then the streams could come
     * from different edits.
     */
    inputstream[] ins = new inputstream[valuecount];19     ... 
    return new snapshot(key, entry.sequencenumber, ins);
 }

    我们可以看到,这个方法最终返回了一个snapshot对象,并以我们要获取的缓存对象的key作为构造参数之一。snapshot是disklrucache的内部类,它包含一个getinputstream方法,通过这个方法可以获取相应缓存对象的输入流,得到了这个输入流,我们就可以进一步获取到bitmap对象了。在获取缓存的bitmap时,我们通常都要对它进行一些预处理,主要就是通过设置insamplesize来适当的缩放图片,以防止出现oom。我们之前已经介绍过如何高效加载bitmap,在那篇文章里我们的图片来源于resources。尽管现在我们的图片来源是流对象,但是计算insamplesize的方法是一样的,只不过我们不再使用decoderesource方法而是使用decodefiledescriptor方法。

相关的代码如下:

bitmap bitmap = null;
string key = getkeyfromurl(url);
disklrucache.snapshot snapshot = mdisklrucache.get(key);
if (snapshot != null) {
  fileinputstream fileinputstream = (fileinputstream) snapshot.getinputstream(0); //参数表示索引,同之前的newoutputstream一样
  filedescriptor filedescriptor = fileinputstream.getfd();
  bitmap = decodesampledbitmapfromfd(filedescriptor, dstwidth, dstheight);
  if (bitmap != null) {
    addbitmaptomemorycache(key, bitmap);
  }
}

 

      第7行我们调用了decodesampledbitmapfromfd来从fileinputstream的文件描述符中解析出bitmap,decodesampledbitmapfromfd方法的定义如下:

public bitmap decodesampledbitmapfromfd(filedescriptor fd, int dstwidth, int dstheight) {
  final bitmapfactory.options options = new bitmapfactory.options();
  options.injustdecodebounds = true;
  bitmapfactory.decodefiledescriptor(fd, null, options);
  //calinsamplesize方法的实现请见“android开发之高效加载bitmap”这篇博文
  options.insamplesize = calinsamplesize(options, dstwidth, dstheight);
  options.injustdecodebounds = false;
  return bitmapfactory.decodefiledescriptor(fd, null, options);
}

     第9行我们调用了addbitmaptomemorycache方法把获取到的bitmap加入到内存缓存中,关于这一方法的具体实现下文会进行介绍。

三、图片加载框架的具体实现
1. 图片的加载

(1)同步加载
    同步加载的相关代码需要在工作者线程中执行,因为其中涉及到对网络的访问,并且可能是耗时操作。同步加载的大致步骤如下:首先尝试从内存缓存中加载bitmap,若不存在再从磁盘缓存中加载,若不存在则从网络中获取并添加到磁盘缓存中。同步加载的代码如下:

public bitmap loadbitmap(string url, int dstwidth, int dstheight) {
  bitmap bitmap = loadfrommemory(url);
  if (bitmap != null) {
    return bitmap;
  }
  //内存缓存中不存在相应图片
  try {
    bitmap = loadfromdisk(url, dstwidth, dstheight);
    if (bitmap != null) {
      return bitmap;
    }
    //磁盘缓存中也不存在相应图片
    bitmap = loadfromnet(url, dstwidth, dstheight);
  } catch (ioexception e) {
    e.printstacktrace();
  }

  return bitmap;
}

    loadbitmapfromnet方法的功能是从网络上获取指定url的图片,并根据给定的dstwidth和dstheight对它进行缩放,返回缩放后的图片。loadbitmapfromdisk方法则是从磁盘缓存中获取并缩放,而后返回缩放后的图片。关于这两个方法的实现在下面“图片的缓存”部分我们会具体介绍。下面我们先来看看异步加载图片的实现。 

(2)异步加载
    异步加载图片在实际开发中更经常被使用,通常我们希望图片加载框架帮我们去加载图片,我们接着干别的活,等到图片加载好了,图片加载框架会负责将它显示在我们给定的imageview中。我们可以使用线程池去执行异步加载任务,加载好后通过handler来更新ui(将图片显示在imageview中)。相关代码如下所示:

public void displayimage(string url, imageview imageview, int dstwidth, int widthheight) {
  imageview.settag(img_url, url);
  bitmap bitmap = loadfrommemory(url);
  if (bitmap != null) {
    imageview.setimagebitmap(bitmap);
    return;
  }
  
  runnable loadbitmaptask = new runnable() {
    @override
    public void run() {
      bitmap bitmap = loadbitmap(url, dstwidth, dstheigth);
      if (bitmap != null) {
        //result是我们自定义的类,封装了返回的bitmap以及它的url和作为它的容器的imageview
        result result = new result(bitmap, url, imageview);
        //mmainhandler为主线程中创建的handler
        message msg = mmainhandler.obtainmessage(message_send_result, result);
        msg.sendtotarget();
       }
    }
  };
  threadpoolexecutor.execute(loadbitmaptask);
}

    从以上代码我们可以看到,异步加载与同步加载之间的区别在于,异步加载把耗时任务放入了线程池中执行。同步加载需要我们创建一个线程并在新线程中执行loadbitmap方法,使用异步加载我们只需传入url、imageview等参数,图片加载框架负责使用线程池在后台执行图片加载任务,加载成功后会通过发送消息给主线程来实现把bitmap显示在imageview中。我们来简单的解释下obtainmessage这个方法,我们传入了两个参数,第一个参数代表消息的what属性,这时个int值,相当于我们给消息定的一个标识,来区分不同的消息;第二个参数代表消息的obj属性,表示我们附带的一个数据对象,就好比我们发email时带的附件。obtainmessage用于从内部的消息池中获取一个消息,就像线程池对线程的复用一样,通过这个方法获取校区更加高效。获取了消息并设置好它的what、obj后,我们在第18行调用sendtotarget方法来发送消息。

下面我们来看看mmainhandler和threadpoolexecutor的创建代码:

private static final int core_pool_size = cpu_count + 1; //corepoolsize为cpu数加1
private static final int max_pool_size = 2 * cpu_count + 1; //maxpoolsize为2倍的cpu数加1
private static final long keep_alive = 5l; //存活时间为5s

public static final executor threadpoolexecutor = new threadpoolexecutor(core_pool_size, max_pool_size, keep_alive, timeunit.seconds, new linkedblockingqueue<runnable>());

private handler mmainhandler = new handler(looper.getmainlooper()) {
  @override
  public void handlemessage(message msg) {
    result result = (result) msg.what;
    imageview imageview = result.imageview;
    string url = (string) imageview.gettag(img_url);
    if (url.equals(result.url)) {
      imageview.setimagebitmap(result.bitmap);
    } else {
      log.w(tag, "the url associated with imageview has changed");
    }
  };
};

    从以上代码中我们可以看到创建mmainhandler时使用了主线程的looper,因此构造mmainhandler的代码可以放在子线程中执行。另外,注意以上代码中我们在给imageview设置图片时首先判断了下它的url是否等于result中的url,若相等才显示。我们知道listview会对其中item的view进行复用,刚移出屏幕的item的view会被即将显示的item所复用。那么考虑这样一个场景:刚移出的item的view中的图片还在未加载完成,而这个view被新显示的item复用时图片加载好了,那么图片就会显示在新item处,这显然不是我们想看到的。因此我们通过判断imageview的url是否与刚加载完的图片的url是否相等,并在

只有两者相等时才显示,就可以避免以上提到的情况。

 2. 图片的缓存

(1)缓存的创建
我们在图片加载框架类(freeimageloader)的构造方法中初始化lrucache和disklrucache,相关代码如下:

private lrucache<string, bitmap> mmemorycache;
private disklrucache mdisklrucache;

private imageloader(context context) {
  mcontext = context.getapplicationcontext();
  int maxmemory = (int) (runtime.getruntime().maxmemory() /1024);
  int cachesize = maxmemory / 8;
  mmemorysize = new lrucache<string, bitmap>(cachesize) {
    @override
    protected int sizeof(string key, bitmap bitmap) {
      return bitmap.getbytecount() / 1024;
    }
  };
  file diskcachedir = getappcachedir(mcontext, "images");
  if (!diskcachedir.exists()) {
    diskcachedir.mkdirs();
  }
  if (diskcachedir.getusablespace() > disk_cache_size) { 
    //剩余空间大于我们指定的磁盘缓存大小
    try {
      mdisklrucache = disklrucache.open(diskcachedir, 1, 1, disk_cache_size);
    } catch (ioexception e) {
      e.printstacktrace();
    }
  }
}

(2)缓存的获取与添加
内存缓存的添加与获取我们已经介绍过,只需调用lrucache的put与get方法,示例代码如下:

private void addtomemorycache(string key, bitmap bitmap) {
  if (getfrommemorycache(key) == null) {
    //不存在时才添加
    mmemorycache.put(key, bitmap);
  }
}

private bitmap getfrommemorycache(string key) {
  return mmemorycache.get(key);
}
 

    接下来我们看一下如何从磁盘缓存中获取bitmap:

private loadfromdiskcache(string url, int dstwidth, int dstheight) throws ioexception {
  if (looper.mylooper() == looper.getmainlooper()) {
    //当前运行在主线程,报错
    log.w(tag, "should not bitmap in main thread");
  }
  
  if (mdisklrucache == null) {
    return null;
  }

  bitmap bitmap = null;
  string key = getkeyfromurl(url);
  disklrucache.snapshot snapshot = mdisklrucache.get(key);
  if (snapshot != null) {
    fileinputstream fileinputstream = (fileinputstream) snapshot.getinputstream(0);
    filedescriptor filedescriptor = fileinputstream.getfd();
    bitmap = decodesampledbitmapfromfd(filedescriptor, dstwidth, dstheight);
    if (bitmap != null) {
      addtomemorycache(key, bitmap);
    }
  }

  return bitmap;
}
  

     把bitmap添加到磁盘缓存中的工作在loadfromnet方法中完成,当从网络上成功获取图片后,会把它存入磁盘缓存中。相关代码如下:

private bitmap loadfromnet(string url, int dstwidth, int dstheight) throws ioexception {
  if (looper.mylooper() == looper.getmainlooper()) {
    throw new runtimeexception("do not load bitmap in main thread.");
  }
  
  if (mdisklrucache == null) {
    return null;
  }
  
  string key = getkeyfromurl(url);
  disklrucache.editor editor = mdisklrucache.edit(key);
  if (editor != null) {
    outputstream outputstream = editor.newoutputstream(0);
    if (getstreamfromurl(url, outputstream)) {
      editor.commit();
    } else {
      editor.abort();
    }
    mdisklrucache.flush();
  }
  return loadfromdiskcache(url, dstwidth, dstheight);
} 

    以上代码的大概逻辑是:当确认当前不在主线程并且mdisklrucache不为空时,从网络上得到图片并保存到磁盘缓存,然后从磁盘缓存中得到图片并返回。

    以上贴出的两段代码在最开头都判断了是否在主线程中,对于loadfromdiskcache方法来说,由于磁盘io相对耗时,不应该在主线程中运行,所以只会在日志输出一个警告;而对于loadfromnet方法来说,由于在主线程中访问网络是不允许的,因此若发现在主线程,直接抛出一个异常,这样做可以避免做了一堆准备工作后才发现位于主线程中不能访问网络(即我们提早抛出了异常,防止做无用功)。

    另外,我们在以上两段代码中都对mdisklrucache是否为空进行了判断。这也是很必要的,设想我们做了一堆工作后发现磁盘缓存根本还没有初始化,岂不是很冤枉。我们通过两个if判断可以尽量避免做无用功。

     现在我们已经实现了一个简洁的图片加载框架,下面我们来看看它的实际使用性能如何。 

四、简单的性能测试
     关于性能优化的姿势,android developer已经给出了最佳实践方案,胡凯大神整理了官方的性能优化典范,请见这里:android性能专题。这里我们主要从内存分配和图片的平均加载时间这两个方面来看一下我们的图片加载框架是否能达到勉强可用的程度。完整的demo请见这里:freeimageloader

1. 内存分配情况

    运行我们的demo,待图片加载完全,我们用adb看一下我们的应用的内存分配情况,我这里得到的情况如下图所示:

    从上图我们可以看到,dalvik heap分配的内存为18003kb, native heap则分配了6212kb。下面我们来看一下freeimageloader平均每张图片的加载时间。

2. 平均加载时间

    这里我们获取平均加载时间的方法非常直接,基本思想是如以下所示:

//加载图片前的时间点
long beforetime = system.currenttimemillis();
//加载图片完成的时间点
long aftertime = system.currenttimemillis();
//total为图片的总数,avertime为加载每张图片所需的平均时间
int avertime = (int) ((aftertime - beforetime) / total)

    然后我们维护一个计数值counts,每加载完一张就加1,当counts为total时我们便调用一个回调方法onafterload,在这个方法中获取当前时间点并计算平均加载时间。具体的代码请看上面给出的demo地址。

    我这里测试加载30张图片时,平均每张所需时间为1.265s。下面我们来用universal image loader来加载这30张图片,并与我们的freeimageloader比较一下。

 3. 与uil的比较

    我这里用uil加载图片完成后,得到的内存情况如下:

     我们可以看到在,native heap的分配上,freeimageloader与uil差不多;在dalvik heap分配上,uil的大小快达到了freeimageloader的2倍。由于框架的量级不同,这说明不了freeimageloader在内存占用上优于uil,但通过这个比较我们可以认为我们刚刚实现的框架还是勉强可用的:)

     我们再来看一下uil的平均加载时间,我这里测试的结果是1.516ms,考虑到框架量级的差异,看来我们的框架在加载时间上还有提升空间。 

五、更进一步
    经过以上的步骤,我们可以看到,实现一个具有基本功能的图片加载框架并不复杂,但我们可以做的还有更多:

现在的异步加载图片方法需要显式提供我们期望的图片大小,一个实用的框架应该能够根据给定的imageview自动计算;
整个框架封装在一个类中,模块化方面显然还可以做的更好;
不具备一个成熟的图片加载框架应该具有的各种功能...

以上就是本文的全部内容,希望对大家的学习有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网