Java对象的4中引用类型

来源:互联网 发布:今天淘宝怎么进不去了 编辑:程序博客网 时间:2024/05/29 08:21

Java对象的4中引用类型


    对于需要长期运行的应用程序来说,如果无用的对象所占用的内存空间不能得到即时的释放的话,那么在一个局部的时间段内便形成了事实上的内存泄露

    以前我们学过,如果要及时地释放内存,最稳妥的方法就是使用完对象之后,立刻执行"object=null"语句。当然,这也是一种理想状态。

    JDK里面引入了4种对象引用类型,可以算是强行的调用System.gc()这个的垃圾回收的方法了。


强引用(StrongReference)强引用不会被GC回收,并且在java.lang.ref里也没有实际的对应类型。

举个例子来说:Object obj = new Object();这里的obj引用便是一个强引用,不会被GC回收。


软引用(SoftReference)被软引用的对象,如果内存空间足够,垃圾回收器是不会回收它的,如果内存空间不足,垃圾回收器将回收这些对象占用的内存空间。软件引用对应着java.lang.ref.SoftReference类,一个对象如果要被软引用,只需将其作为参数传入SoftReference类的构造方法中就行了。

软引用在JVM报告内存不足的时候才会被GC回收,否则不会回收,正是由于这种特性,软引用在caching中用处广泛。

软引用的用法:

        Object obj = new Object();
    SoftReference<Object> softRef =new SoftReference(obj);
// 使用 softRef.get() 获取软引用所引用的对象
    Object objg = softRef.get();


弱引用(WeakReference)与前面的软引用相比,被弱引用了的对象拥有更短的内存时间(也就是生命周期)。垃圾回收器一旦发现了被弱引用的对象,不管当前内存空间是不是足够,都会回收它的内存,弱引用对应着java.lang.ref.WeakReference类,同样的道理。一个对象如果想被弱引用,只需将其作为参数传入WeakReference类的构造方法中就行了。当GC一但发现了弱引用对象,将会释放WeakReference所引用的对象。弱引用使用方法与软引用类似,但回收策略不同。


虚引用(PhantomReference):虚引用不是一种真实可用的引用类型,完全可以视为一种“形同虚设”的引用类型。设计虚引用的目的在于结合引用关联队列,实现对对象引用关系的跟踪。虚引用对应着java.lang.ref.PhantomReference类。一个对象如果要被虚引用,只需将其作为参数传入PhantomReference类的构造方法中就行了,同时作为参数传入的还有引用关联队列java.lang.ref.ReferenceQueue的对象实例

当GC一但发现了虚引用对象,将会将PhantomReference对象插入ReferenceQueue队列,而此时PhantomReference所指向的对象并没有被GC回收,而是要等到ReferenceQueue被真正的处理后才会被回收。虚引用的用法:


SoftReference,WeakReference,PhantomReference类都继承自java.lang.ref.Reference抽象类。Reference抽象类定义了clear()方法用于撤销引用关系,get()方法用于返回被引用的对象。


摘抄一段代码示例:


import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.Set;
import java.util.HashSet;

public class TestReferences{

publicstatic void main(String[] args){

int length=10;


//创建length个MyObject对象的强引用

Set a = newHashSet();
for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{
MyObject ref=new MyObject("Hard_" + i);
System.out.println("创建强引用:" +ref);
a.add(ref);
}
//a=null;
System.gc();

//创建length个MyObject对象的软引用
Set<sa = newHashSet<();
for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{
SoftReference ref=newSoftReference(newMyObject("Soft_" + i));
System.out.println("创建软引用:" +ref.get());
sa.add(ref);
}
System.gc();

for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{

MyObject ref=new MyObject("Hard_" + i);

System.out.println("创建强引用:" +ref);

a.add(ref);

}

//a=null;

System.gc();


//创建length个MyObject对象的软引用

Set<sa = newHashSet<();
for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{
SoftReference ref=newSoftReference(newMyObject("Soft_" + i));
System.out.println("创建软引用:" +ref.get());
sa.add(ref);
}
System.gc();

for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{

SoftReference ref=newSoftReference(newMyObject("Soft_" + i));
System.out.println("创建软引用:" +ref.get());
sa.add(ref);
}
System.gc();

System.out.println("创建软引用:" +ref.get());

sa.add(ref);

}

System.gc();

//创建length个MyObject对象的弱引用

Set<wa = newHashSet<();
for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{
WeakReference ref=newWeakReference(newMyObject("Weak_" + i));
System.out.println("创建弱引用:" +ref.get());
wa.add(ref);
}
System.gc();

for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{

WeakReference ref=newWeakReference(newMyObject("Weak_" + i));
System.out.println("创建弱引用:" +ref.get());
wa.add(ref);
}
System.gc();

System.out.println("创建弱引用:" +ref.get());

wa.add(ref);

}

System.gc();

//创建length个MyObject对象的虚引用

ReferenceQueue rq = newReferenceQueue();
Set<pa = newHashSet<();
for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{
PhantomReference ref = newPhantomReference(newMyObject("Phantom_" + i), rq);
System.out.println("创建虚引用:" +ref.get());
pa.add(ref);
}
System.gc();
}
}

Set<pa = newHashSet<();
for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{
PhantomReference ref = newPhantomReference(newMyObject("Phantom_" + i), rq);
System.out.println("创建虚引用:" +ref.get());
pa.add(ref);
}
System.gc();
}
}

for(int i = 0; i < length ibr style='font-size:14px;font-style:normal;font-weight:normal;font-family:simsun;color:rgb(70, 70, 70);' />{

PhantomReference ref = newPhantomReference(newMyObject("Phantom_" + i), rq);
System.out.println("创建虚引用:" +ref.get());
pa.add(ref);
}
System.gc();
}
}

System.out.println("创建虚引用:" +ref.get());

pa.add(ref);

}

System.gc();

}

}


class MyObject{

privateString id;

publicMyObject(String id)

{

this.id = id;

}

publicString toString()

{

return id;

}

publicvoid finalize()

{

System.out.println("回收对象:" + id);

}

}


Object obj = new Object();
ReferenceQueue<Object> refQueue =new ReferenceQueue<Object>();
PhantomReference<Object> phanRef =new PhantomReference<Object>(obj, refQueue);
// 调用phanRef.get()不管在什么情况下会一直返回null
Object objg = phanRef.get();
// 如果obj被置为null,当GC发现了虚引用,GC会将phanRef插入进我们之前创建时传入的refQueue队列
// 注意,此时phanRef所引用的obj对象,并没有被GC回收,在我们显式地调用refQueue.poll返回phanRef之后
// 当GC第二次发现虚引用,而此时JVM将phanRef插入到refQueue会插入失败,此时GC才会对obj进行回收
Reference<? extends Object> phanRefP = refQueue.poll();


看了简单的定义之后,我们结合着代码来测试一下,强引用就不用说了,软引用的描述也很清楚,关键是 “弱引用” 与 “虚引用”。

弱引用


public static void main(String[] args)throws InterruptedException {
    Object obj =new Object();
    ReferenceQueue<Object> refQueue =new ReferenceQueue<Object>();
    WeakReference<Object> weakRef =new WeakReference<Object>(obj, refQueue);
    System.out.println(weakRef.get());
    System.out.println(refQueue.poll());
    obj =null;
    System.gc();
    System.out.println(weakRef.get());
    System.out.println(refQueue.poll());
}


由于System.gc()是告诉JVM这是一个执行GC的好时机,但具体执不执行由JVM决定,因此当JVM决定执行GC,得到的结果便是(事实上这段代码一般都会执行GC):

java.lang.Object@de6ced
  null
  null
java.lang.ref.WeakReference@1fb8ee3

从执行结果得知,通过调用weakRef.get()我们得到了obj对象,由于没有执行GC,因此refQueue.poll()返回的null,当我们把obj = null;此时没有引用指向堆中的obj对象了,这里JVM执行了一次GC,我们通过weakRef.get()发现返回了null,而refQueue.poll()返回了WeakReference对象,因此JVM在对obj进行了回收之后,才将weakRef插入到refQueue队列中。

虚引用

?
1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args)throws InterruptedException {
    Object obj =new Object();
    ReferenceQueue<Object> refQueue =new ReferenceQueue<Object>();
    PhantomReference<Object> phanRef =new PhantomReference<Object>(obj, refQueue);
    System.out.println(phanRef.get());
    System.out.println(refQueue.poll());
    obj =null;
    System.gc();
    System.out.println(phanRef.get());
    System.out.println(refQueue.poll());
}

同样,当JVM执行了GC,得到的结果便是:

  null
  null
  null
java.lang.ref.PhantomReference@1fb8ee3

从执行结果得知,我们先前说的没有错,phanRef.get()不管在什么情况下,都会返回null,而当JVM执行GC发现虚引用之后,JVM并没有回收obj,而是将PhantomReference对象插入到对应的虚引用队列refQueue中,当调用refQueue.poll()返回PhantomReference对象时,poll方法会先把PhantomReference的持有队列queue(ReferenceQueue<? super T>)置为NULL,NULL对象继承自ReferenceQueue,将enqueue(Reference paramReference)方法覆盖为return false,而此时obj再次被GC发现时,JVM再将PhantomReference插入到NULL队列中便会插入失败返回false,此时GC便会回收obj。事实上通过这段代码我们也的却看不出来obj是否被回收,但通过 PhantomReference 的javadoc注释中有一句是这样写的:

Once the garbage collector decides that an object obj is phantom-reachable, it is being enqueued on the corresponding queue, but its referent is not cleared. That is, the reference queue of the phantom reference must explicitly be processed by some application code.

翻译一下(这句话很简单,我相信很多人应该也看得懂):

一旦GC决定一个“obj”是虚可达的,它(指PhantomReference)将会被入队到对应的队列,但是它的指代并没有被清除。也就是说,虚引用的引用队列一定要明确地被一些应用程序代码所处理。

弱引用与虚引用的用处.

  软引用很明显可以用来制作caching和pooling,而弱引用与虚引用呢?其实用处也很大,首先我们来看看弱引用,举个例子:

?
1
2
3
4
5
6
7
class Registry {
    privateSet registeredObjects = newHashSet();
 
    publicvoid register(Object object) {
        registeredObjects.add( object );
    }
}

所有我添加进 registeredObjects 中的object永远不会被GC回收,因为这里有个强引用保存在registeredObjects里,另一方面如果我把代码改为如下:

?
1
2
3
4
5
6
7
class Registry {
     privateSet registeredObjects = newHashSet();
  
     publicvoid register(Object object) {
         registeredObjects.add(new WeakReference(object) );
     }
 }

  现在如果GC想要回收registeredObjects中的object,便能够实现了,同样在使用HashMap如果想实现如上的效果,一种更好的实现是使用WeakHashMap。

而虚引用呢?我们先来看看javadoc的部分说明:

Phantom references are useful for implementing cleanup operations that are necessary before an object gets garbage-collected. They are sometimes more flexible than thefinalize() method.

翻译一下:

虚引用在实现一个对象被回收之前必须做清理操作是很有用的。有时候,他们比finalize()方法更灵活。

很明显的,虚引用可以用来做对象被回收之前的清理工作。


二.四种引用类型的比较:

类型目的作用触发GC条件实现类强引用普通引用类型,只要对象的引用是强引用,他们就不会被垃圾收集普通引用任何对象如果不是强引用都可以被垃圾收集默认类型软引用在内存足够的时候,对象不会被垃圾收集为了保证即使对象没有任何引用指向它的时候也不会被垃圾收集,防止有引用再次指向这个对象在第一次GC后,JVM需要回收更多的空间java.lang.ref.SoftReference弱引用在对象可触及的状态下不会被垃圾收集如果对象不再被引用会被自动回收GC后对象只有弱引用java.lang.ref.WeakReference
java.util.WeakHashMap
虚引用让你可以清理已经执行finalize方法,但是还没有回收内存的对象特殊清理finalize方法执行之后java.lang.ref.PhantomReference



Android中的缓存处理及异步加载图片类的封装


一、缓存介绍:

(一)、Android中缓存的必要性:
智能手机的缓存管理应用非常的普遍和需要,是提高用户体验的有效手段之一。

1、没有缓存的弊端:
  • 流量开销:对于客户端——服务器端应用,从远程获取图片算是经常要用的一个功能,而图片资源往往会消耗比较大的流量。
  • 加载速度:如果应用中图片加载速度很慢的话,那么用户体验会非常糟糕。
  • 那么如何处理好图片资源的获取和管理呢?异步下载+本地缓存
2、缓存带来的好处:
  • 1. 服务器的压力大大减小;
  • 2. 客户端的响应速度大大变快(用户体验好);
  • 3. 客户端的数据加载出错情况大大较少,大大提高了应有的稳定性(用户体验好);
  • 4. 一定程度上可以支持离线浏览(或者说为离线浏览提供了技术支持)。
3、缓存管理的应用场景:
  • 1. 提供网络服务的应用;
  • 2. 数据更新不需要实时更新,即便是允许3-5分钟的延迟也建议采用缓存机制;
  • 3. 缓存的过期时间是可以接受的(不会因为缓存带来的好处,导致某些数据因为更新不及时而影响产品的形象等)
4、大位图导致内存开销大的原因是什么?
  • 1.下载或加载的过程中容易导致阻塞;
  • 大位图Bitmap对象是png格式的图片的30至100倍;
  • 2.大位图在加载到ImageView控件前的解码过程;BitmapFactory.decodeFile()会有内存消耗。

5、缓存设计的要点:
  • 1.命中率;
  • 2.合理分配占用的空间;
  • 3.合理的缓存层级。

(二)、加载图片的正确流程是:“内存-文件-网络 三层cache策略

1、先从内存缓存中获取,取到则返回,取不到则进行下一步;
2、从文件缓存中获取,取到则返回并更新到内存缓存,取不到则进行下一步;
3、从网络下载图片,并更新到内存缓存和文件缓存。

具体说就是:同一张图片只要从网络获取一次,然后在本地缓存起来,之后加载同一张图片时就从缓存中去加载。从内存缓存读取图片是最快的,但是因为内存容量有限,所以最好再加上文件缓存。文件缓存空间也不是无限大的,容量越大读取效率越低,因此可以设置一个限定大小比如10M,或者限定保存时间比如一天。
在键值对(key-value)中,图片缓存的key是图片url的hash值,value就是bitmap。所以,按照这个逻辑,只要一个url被下载过,其图片就被缓存起来了。


(三)、内存缓存分类:

在JDK1.2以前的版本中,当一个对象不被任何变量引用,那么程序就无法再使用这个对象。也就是说,只有对象处于可触及状态,程序才能使用它。这 就像在日常生活中,从商店购买了某样物品后,如果有用,就一直保留它,否则就把它扔到垃圾箱,由清洁工人收走。一般说来,如果物品已经被扔到垃圾箱,想再 把它捡回来使用就不可能了。但有时候情况并不这么简单,你可能会遇到类似鸡肋一样的物品,食之无味,弃之可惜。这种物品现在已经无用了,保留它会占空间,但是立刻扔掉它也不划算,因为也许将来还会派用场。对于这样的可有可无的物品,一种折衷的处理办法是:如果家里空间足够,就先把它保留在家里,如果家里空间不够,即使把家里所有的垃圾清除,还是无法容纳那些必不可少的生活用品,那么再扔掉这些可有可无的物品。
从JDK1.2版本开始,把对象的引用分为四种级别,从而使程序能更加灵活的控制对象的生命周期。
这四种级别由高到低依次为:强引用软引用弱引用虚引用


下图为对象层次的引用


 

1、强引用:(在Android中LruCache就是强引用缓存

平时我们编程的时候例如:Object object=new Object();那object就是一个强引用了。如果一个对象具有强引用,那就类似于必不可少的生活用品,垃圾回收器绝不会回收它。当内存空间不足,Java虚拟机宁愿抛出OOM异常,使程序异常终止,也不会回收具有强引用的对象来解决内存不足问题。

 

2、软引用(SoftReference):

软引用类似于可有可无的生活用品。如果内存空间足够,垃圾回收器就不会回收它,如果内存空间不足了,就会回收这些对象的内存。只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。 软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收,Java虚拟机就会把这个软引用加入到与之关联的引用队列中

使用软引用能防止内存泄露,增强程序的健壮性。 


3、弱引用(WeakReference):   

弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。不过,由于垃圾回收器是一个优先级很低的线程, 因此不一定会很快发现那些只具有弱引用的对象。  弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java虚拟机就会把这个弱引用加入到与之关联的引用队列中。 

 

4、虚引用(PhantomReference)   

 "虚引用"顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收。 虚引用主要用来跟踪对象被垃圾回收的活动

虚引用与软引用和弱引用的一个区别在于:虚引用必须和引用队列(ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之关联的引用队列中。程序可以通过判断引用队列中是否已经加入了虚引用,来了解被引用的对象是否将要被垃圾回收。程序如果发现某个虚引用已经被加入到引用队列,那么就可以在所引用的对象的内存被回收之前采取必要的行动。 

 

【相关应用:】

在java.lang.ref包中提供了三个类:SoftReference类、WeakReference类和PhantomReference类,它们分别代表软引用、弱引用和虚引用。ReferenceQueue类表示引用队列,它可以和这三种引用类联合使用,以便跟踪Java虚拟机回收所引用的对 象的活动。


        Lru:Least Recently Used 

        近期最少使用算法,是一种页面置换算法,其思想是在缓存的页面数目固定的情况下,那些最近使用次数最少的页面将被移出,对于我们的内存缓存来说,强引用缓存大小固定为4M,如果当缓存的图片大于4M的时候,有些图片就会被从强引用缓存中删除,哪些图片会被删除呢,就是那些近期使用次数最少的图片。


(四)、内存保存:

在内存中保存的话,只能保存一定的量,而不能一直往里面放,需要设置数据的过期时间、LRU等算法。这里有一个方法是把常用的数据放到一个缓存中(A),不常用的放到另外一个缓存中(B)。当要获取数据时先从A中去获取,如果A中不存在那么再去B中获取。B中的数据主要是A中LRU出来的数据,这里的内存回收主要针对B内存,从而保持A中的数据可以有效的被命中。




(五)、缓存的案例代码:

publicclass MainActivity extends Activity {
privatefinalstatic String TAG = "MainActivity";
private ImageView imageView_main;
private ProgressDialog pDialog = null;
private String urlString = "http://c.hiphotos.baidu.com/image/pic/item/5366d0160924ab18dd54473737fae6cd7b890b6b.jpg";
// private String urlString = "http://www.baidu.com/img/bdlogo.gif";
private LruCache<String, Bitmap> lruCache = null;
private LinkedHashMap<String, SoftReference<Bitmap>> softMap = new LinkedHashMap<String, SoftReference<Bitmap>>();
private Handler handler = new Handler() {
publicvoid handleMessage(Message msg) {
switch (msg.what) {
case 0:
pDialog.show();
break;
case 1:
Bitmap bm = (Bitmap) msg.obj;
if (bm != null) {
imageView_main.setImageBitmap(bm);
}
pDialog.dismiss();
break;
default:
break;
}
}
};


@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_main = (ImageView) findViewById(R.id.imageView_main);


pDialog = new ProgressDialog(this);
pDialog.setIcon(R.drawable.ic_launcher);
pDialog.setTitle("提示:");
pDialog.setMessage("数据加载中。。。");


// int memClass = ((ActivityManager)
// getSystemService(Context.ACTIVITY_SERVICE))
// .getMemoryClass();
int memoryCount = (int) Runtime.getRuntime().maxMemory();
// 获取剩余内存的8分之一作为缓存
int cacheSize = memoryCount / 8;


Log.i(TAG, "==" + cacheSize);


lruCache = new MyLruCache(cacheSize);// 这个初始化值是如何定义的?
}


class MyLruCache extends LruCache<String, Bitmap> {
public MyLruCache(int maxSize) {
super(maxSize);
}


@Override
protectedint sizeOf(String key, Bitmap value) {
// return value.getHeight() * value.getWidth() * 4;
// Bitmap图片的一个像素是4个字节
Log.i(TAG, "==" + value.getByteCount());
return value.getByteCount();
}


@Override
protectedvoid entryRemoved(boolean evicted, String key,
Bitmap oldValue, Bitmap newValue) {
if (evicted) {
SoftReference<Bitmap> softReference = new SoftReference<Bitmap>(
oldValue);
softMap.put(key, softReference);
}
}
}


publicvoid clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_submit:
Bitmap bm = getBitmapFromMemoryCache(urlString);
if (bm != null) {
imageView_main.setImageBitmap(bm);
Log.i(TAG, "==从缓存中获取到的图片");
} else {
new Thread(new Runnable() {
@Override
publicvoid run() {
handler.sendEmptyMessage(0);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(urlString);
try {
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
byte[] data = EntityUtils.toByteArray(response
.getEntity());


Log.i(TAG, "==文件尺寸:" + data.length);
Bitmap bm = BitmapFactory.decodeByteArray(data,
0, data.length);
// 放入强缓存
lruCache.put(urlString, bm);
Log.i(TAG, "==放入强缓存ok");


Message msg = Message.obtain();
msg.obj = bm;
msg.what = 1;
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
break;
default:
break;
}
}


public Bitmap getBitmapFromMemoryCache(String key) {
// 1.先从强引用中获取
Bitmap bitmap = null;
bitmap = lruCache.get(key);
if (bitmap != null) {
Log.i(TAG, "==从强引用中找到");
return bitmap;
} else {
// 2.如果强引用中没有找到的话 如果软引用中存在就将它移到强引用中 然后软引用移除
SoftReference<Bitmap> softReference = softMap.get(key);
if (softReference != null) {
bitmap = softReference.get();
Log.i(TAG, "==从软引用中找到");
if (bitmap != null) {
// 添加到强引用中
lruCache.put(key, bitmap);
Log.i(TAG, "==添加到强引用中");


// 从软引用集合中移除
softMap.remove(key);
Log.i(TAG, "==从软引用中移除");
return bitmap;
} else {
softMap.remove(key);
}
}
}
returnnull;
}


@Override
publicboolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.next, menu);
returntrue;
}
}



二、封装异步任务类:

(一)、AsynTaskHelper的核心代码:

publicclass AsynTaskHelper {

privatestaticfinal String TAG = "AsynTaskHelper";




publicvoid downloadData(String url, OnDataDownloadListener downloadListener) {

new MyTask(downloadListener).execute(url);

}




privateclass MyTask extends AsyncTask<String, Void, byte[]> {

private OnDataDownloadListener downloadListener;




public MyTask(OnDataDownloadListener downloadListener) {

this.downloadListener = downloadListener;

}




@Override

protectedbyte[] doInBackground(String... params) {

BufferedInputStream bis = null;

ByteArrayOutputStream baos = new ByteArrayOutputStream();

try {

URL url = new URL(params[0]);

HttpURLConnection httpConn = (HttpURLConnection) url

.openConnection();

httpConn.setDoInput(true);

httpConn.setRequestMethod("GET");

httpConn.connect();

if (httpConn.getResponseCode() == 200) {

bis = new BufferedInputStream(httpConn.getInputStream());

byte[] buffer = newbyte[1024 * 8];

int c = 0;

while ((c = bis.read(buffer)) != -1) {

baos.write(buffer, 0, c);

baos.flush();

}

return baos.toByteArray();

}

} catch (Exception e) {

e.printStackTrace();

}

returnnull;

}




@Override

protectedvoid onPostExecute(byte[] result) {

// 通过回调接口来传递数据

downloadListener.onDataDownload(result);

super.onPostExecute(result);

}

}




publicinterface OnDataDownloadListener {

void onDataDownload(byte[] result);

}

}


三、带有缓存的异步加载图片类:

(一)、ImageDownloader的核心代码:

publicclass ImageDownloadHelper {

privatestaticfinal String TAG = "ImageDownloaderHelper";

private HashMap<String, MyAsyncTask> map = new HashMap<String, MyAsyncTask>();

private Map<String, SoftReference<Bitmap>> softCaches = new LinkedHashMap<String, SoftReference<Bitmap>>();

private LruCache<String, Bitmap> lruCache = null;




public ImageDownloadHelper() {

int memoryAmount = (int) Runtime.getRuntime().maxMemory();

// 获取剩余内存的8分之一作为缓存

int cacheSize = memoryAmount / 8;

if (lruCache == null) {

lruCache = new MyLruCache(cacheSize);

}

Log.i(TAG, "==LruCache尺寸:" + cacheSize);

}




/**

*

* @param context

* @param url

* 该mImageView对应的url

* @param mImageView

* @param path

* 文件存储路径

* @param downloadListener

* OnImageDownload回调接口,在onPostExecute()中被调用

*/

publicvoid imageDownload(Context context, String url,

ImageView mImageView, String path,

OnImageDownloadListener downloadListener) {

Bitmap bitmap = null;

// 先从强引用中拿数据

if (lruCache != null) {

bitmap = lruCache.get(url);

}

if (bitmap != null && url.equals(mImageView.getTag())) {

Log.i(TAG, "==从强引用中找到数据");

mImageView.setImageBitmap(bitmap);

} else {

SoftReference<Bitmap> softReference = softCaches.get(url);

if (softReference != null) {

bitmap = softReference.get();

}




// 从软引用中拿数据

if (bitmap != null && url.equals(mImageView.getTag())) {

Log.i(TAG, "==从软引用中找到数据");

// 添加到强引用中

lruCache.put(url, bitmap);

Log.i(TAG, "==添加到强引用中");




// 从软引用集合中移除

softCaches.remove(url);

mImageView.setImageBitmap(bitmap);

} else {

// 从文件缓存中拿数据

String imageName = "";

if (url != null) {

imageName = ImageDownloaderUtil.getInstance().getImageName(

url);

}

bitmap = getBitmapFromFile(context, imageName, path);

if (bitmap != null && url.equals(mImageView.getTag())) {

Log.i(TAG, "==从文件缓存中找到数据");

// 放入强缓存

lruCache.put(url, bitmap);

mImageView.setImageBitmap(bitmap);

} else {

// 从网络中拿数据

if (url != null && needCreateNewTask(mImageView)) {

MyAsyncTask task = new MyAsyncTask(context, url,

mImageView, path, downloadListener);

Log.i(TAG, "==从网络中拿数据");

if (mImageView != null) {

task.execute();

// 将对应的url对应的任务存起来

map.put(url, task);

}

}

}

}

}

}




/**

* 判断是否需要重新创建线程下载图片,如果需要,返回值为true。

*

* @param url

* @param mImageView

* @return

*/

privateboolean needCreateNewTask(ImageView mImageView) {

boolean b = true;

if (mImageView != null) {

String curr_task_url = (String) mImageView.getTag();

if (isTasksContains(curr_task_url)) {

b = false;

}

}

return b;

}




/**

* 检查该url(最终反映的是当前的ImageView的tag,tag会根据position的不同而不同)对应的task是否存在

*

* @param url

* @return

*/

privateboolean isTasksContains(String url) {

boolean b = false;

if (map != null && map.get(url) != null) {

b = true;

}

return b;

}




/**

* 删除map中该url的信息,这一步很重要,不然MyAsyncTask的引用会“一直”存在于map中

*

* @param url

*/

privatevoid removeTaskFromMap(String url) {

if (url != null && map != null && map.get(url) != null) {

map.remove(url);

Log.i(TAG, "当前map的大小==" + map.size());

}

}




/**

* 从文件中拿图片

*

* @param mActivity

* @param imageName

* 图片名字

* @param path

* 图片路径

* @return

*/

private Bitmap getBitmapFromFile(Context context, String imageName,

String path) {

Bitmap bitmap = null;

if (imageName != null) {

File file = null;

String real_path = "";

try {

if (ImageDownloaderUtil.getInstance().hasSDCard()) {

real_path = ImageDownloaderUtil.getInstance().getExtPath()

+ (path != null && path.startsWith("/") ? path

: "/" + path);

} else {

real_path = ImageDownloaderUtil.getInstance()

.getPackagePath(context)

+ (path != null && path.startsWith("/") ? path

: "/" + path);

}

file = new File(real_path, imageName);

if (file.exists())

bitmap = BitmapFactory.decodeStream(new FileInputStream(

file));

} catch (Exception e) {

e.printStackTrace();

bitmap = null;

}

}

return bitmap;

}




/**

* 将下载好的图片存放到文件中

*

* @param path

* 图片路径

* @param mActivity

* @param imageName

* 图片名字

* @param bitmap

* 图片

* @return

*/

privateboolean setBitmapToFile(String path, Context mActivity,

String imageName, Bitmap bitmap) {

File file = null;

String real_path = "";

try {

if (ImageDownloaderUtil.getInstance().hasSDCard()) {

real_path = ImageDownloaderUtil.getInstance().getExtPath()

+ (path != null && path.startsWith("/") ? path : "/"

+ path);

} else {

real_path = ImageDownloaderUtil.getInstance().getPackagePath(

mActivity)

+ (path != null && path.startsWith("/") ? path : "/"

+ path);

}

file = new File(real_path, imageName);

if (!file.exists()) {

File file2 = new File(real_path + "/");

file2.mkdirs();

}

file.createNewFile();

FileOutputStream fos = null;

if (ImageDownloaderUtil.getInstance().hasSDCard()) {

fos = new FileOutputStream(file);

} else {

fos = mActivity.openFileOutput(imageName, Context.MODE_PRIVATE);

}




if (imageName != null

&& (imageName.contains(".png") || imageName

.contains(".PNG"))) {

bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);

} else {

bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);

}

fos.flush();

if (fos != null) {

fos.close();

}

returntrue;

} catch (Exception e) {

e.printStackTrace();

returnfalse;

}

}




/**

* 辅助方法,一般不调用

*

* @param path

* @param mActivity

* @param imageName

*/

privatevoid removeBitmapFromFile(String path, Context mActivity,

String imageName) {

File file = null;

String real_path = "";

try {

if (ImageDownloaderUtil.getInstance().hasSDCard()) {

real_path = ImageDownloaderUtil.getInstance().getExtPath()

+ (path != null && path.startsWith("/") ? path : "/"

+ path);

} else {

real_path = ImageDownloaderUtil.getInstance().getPackagePath(

mActivity)

+ (path != null && path.startsWith("/") ? path : "/"

+ path);

}

file = new File(real_path, imageName);

if (file != null)

file.delete();

} catch (Exception e) {

e.printStackTrace();

}

}




/**

* 异步下载图片的方法

*

* @author

*

*/

privateclass MyAsyncTask extends AsyncTask<String, Void, Bitmap> {

private Context context;

private ImageView mImageView;

private String url;

private OnImageDownloadListener downloadListener;

private String path;




public MyAsyncTask(Context context, String url, ImageView mImageView,

String path, OnImageDownloadListener downloadListener) {

this.context = context;

this.url = url;

this.mImageView = mImageView;

this.path = path;

this.downloadListener = downloadListener;

}




@Override

protected Bitmap doInBackground(String... params) {

Bitmap bm = null;

if (url != null) {

try {

Log.i(TAG, "==访问网络加载图片");

URL urlObj = new URL(url);

HttpURLConnection httpConn = (HttpURLConnection) urlObj

.openConnection();

httpConn.setDoInput(true);

httpConn.setRequestMethod("GET");

httpConn.connect();

if (httpConn.getResponseCode() == 200) {

InputStream is = httpConn.getInputStream();

bm = BitmapFactory.decodeStream(is);

}

String imageName = ImageDownloaderUtil.getInstance()

.getImageName(url);

if (!setBitmapToFile(path, context, imageName, bm)) {

removeBitmapFromFile(path, context, imageName);

}

// 放入强缓存

lruCache.put(url, bm);

Log.i(TAG, "==放入强缓存ok");

} catch (Exception e) {

e.printStackTrace();

}

}

return bm;

}




@Override

protectedvoid onPostExecute(Bitmap result) {

// 回调设置图片

if (downloadListener != null) {

downloadListener.onImageDownload(result, url);

// 该url对应的task已经下载完成,从map中将其删除

removeTaskFromMap(url);

}

super.onPostExecute(result);

}

}




publicinterface OnImageDownloadListener {

void onImageDownload(Bitmap bitmap, String imgUrl);

}




// 定义强引用缓存

class MyLruCache extends LruCache<String, Bitmap> {

public MyLruCache(int maxSize) {

super(maxSize);

}




@Override

protectedint sizeOf(String key, Bitmap value) {

// return value.getHeight() * value.getWidth() * 4;

// Bitmap图片的一个像素是4个字节

return value.getByteCount();

}




@Override

protectedvoid entryRemoved(boolean evicted, String key,

Bitmap oldValue, Bitmap newValue) {




if (evicted) {

SoftReference<Bitmap> softReference = new SoftReference<Bitmap>(

oldValue);

softCaches.put(key, softReference);

}

}

}




staticclass ImageDownloaderUtil {

privatestatic ImageDownloaderUtil util;




private ImageDownloaderUtil() {

}




publicstatic ImageDownloaderUtil getInstance() {

if (util == null) {

util = new ImageDownloaderUtil();

}

returnutil;

}




/**

* 判断是否有sdcard

*

* @return

*/

publicboolean hasSDCard() {

boolean b = false;

if (Environment.MEDIA_MOUNTED.equals(Environment

.getExternalStorageState())) {

b = true;

}

return b;

}




/**

* 得到sdcard路径

*

* @return

*/

public String getExtPath() {

String path = "";

if (hasSDCard()) {

path = Environment.getExternalStorageDirectory().getPath();

}

return path;

}




/**

* 得到包目录

*

* @param mActivity

* @return

*/

public String getPackagePath(Context mActivity) {

return mActivity.getFilesDir().toString();

}




/**

* 根据url得到图片名

*

* @param url

* @return

*/

public String getImageName(String url) {

String imageName = "";

if (url != null) {

imageName = url.substring(url.lastIndexOf("/") + 1);

}

return imageName;

}

}

}


(二)、应用举例:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.item_listview_main, null);
viewHolder.CoverStoryImage = (ImageView) convertView.findViewById(R.id.CoverStoryImage);
viewHolder.CoverStoryName = (TextView) convertView.findViewById(R.id.CoverStoryName);
viewHolder.IssueDate = (TextView) convertView.findViewById(R.id.IssueDate);
viewHolder.Issue = (TextView) convertView.findViewById(R.id.Issue);
viewHolder.IssueYear = (TextView) convertView.findViewById(R.id.IssueYear);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.CoverStoryName.setText(dataList.get(position).get("CoverStoryName"));
viewHolder.IssueDate.setText(dataList.get(position).get("IssueDate"));
viewHolder.Issue.setText(dataList.get(position).get("Issue"));
viewHolder.IssueYear.setText(dataList.get(position).get("IssueYear"));
viewHolder.CoverStoryImage.setImageResource(R.drawable.defaultcovers);
                        // 开始加载图片
final String urlString = dataList.get(position).get("CoverStoryImage");
viewHolder.CoverStoryImage.setTag(urlString);

Log.i(TAG, "settag:" + urlString);
// 方法一:增加了缓存的异步加载图片
if (mDownloader == null) {
mDownloader = new ImageDownloader();
}
if (mDownloader != null) {
// 异步下载图片
mDownloader.imageDownload(urlString,
viewHolder.CoverStoryImage, "/img_temp", context,new ImageDownloader.OnImageDownload() {
@Override
public void onDownloadSuccess(Bitmap bitmap,String imgUrl, ImageView imageView) {
ImageView image_item = (ImageView) imageView.findViewWithTag(imgUrl);
if (image_item != null) {
image_item.setImageBitmap(bitmap);
image_item.setTag(null);

Log.i(TAG, "findViewWithTag:" + imgUrl);
} else {
Log.i(TAG, "imageView is null:" + imgUrl); //???为什么会有为null的时候呢
}
}
});
}

return convertView;
}

class ViewHolder {
private ImageView CoverStoryImage;
private TextView CoverStoryName;
private TextView IssueDate;
private TextView Issue;
private TextView IssueYear;
}









1 0
原创粉丝点击