android优化从网络中加载图片速度。。

从网络中加载图片主要要注意两个方面的问题:

1.内存管理:图片占的内存很大,假如图片数量多,很容易让系统抛出out of memory的异常。

                 同时我们也要注意不同android版本中内存管理的区别。

2.性能:图片的加载速度,和加载图片时不影响UI的流畅性

尤其是在ViewPager,GridView 和ListView等等需要在短时间内加载大量图片时,上面两个问题就更加突出了。。。

要解决上面这个两个问题,我们要用到的技术

1.缩减加载的图片的bitmap

    可以通过实现显示图片的view的大小来计算所需的bitmap,还有可以只首先生成缩略图的方式。

2.使用memoryCache和diskCache(防止activity被外来事件(比如电话)中断后导致内存缓存数据被清除时,

能尽快恢复过来,不要再去网络中拉取图片数据)。

   可以使用系统提供的支持类LruCache和DiskLruCache(android.support.v4),在使用缓存还需要注意

多线程同步的问题(在短时间内间需要发出多个线程,并且这些线程都同时使用一块内存)。

3.I/O操作使用异步加载图片数据,防止阻塞UI线程。

等等。。。。。。

   最后引用android官网的对位图内存管理的一段话:

To set the stage for this lesson, here is how Android's management of bitmap memory has evolved:

  • On Android Android 2.2 (API level 8) and lower, when garbage collection occurs, your app's threads get stopped. This causes a lag that can degrade performance. Android 2.3 adds concurrent garbage collection, which means that the memory is reclaimed soon after a bitmap is no longer referenced.
  • On Android 2.3.3 (API level 10) and lower, the backing pixel data for a bitmap is stored in native memory. It is separate from the bitmap itself, which is stored in the Dalvik heap. The pixel data in native memory is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash. As of Android 3.0 (API level 11), the pixel data is stored on the Dalvik heap along with the associated bitmap.

上面的话,大体的意思是在android2.2以及之前的版本,android进行垃圾回收会导致应用程序的线程产生停顿现象。在android2.3以及以后版本垃圾回收是并发的,不会影响到应用线程,可能会导致没有引用的位图数据会很快被回收。

在adroid2.3.3以及之前的版本像素数据是存在本地内存的,这样导致不会被释放,可能会导致应用程序内存溢出而崩溃。到了android3.0以后像素数据和位图数据一样是保存在java堆中。

 详细的介绍请看官网上面的说明http://developer.android.com/training/displaying-bitmaps/index.html

原文地址:https://www.cnblogs.com/lzl-sml/p/3734621.html