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中用处广泛。
软引用的用法:
弱引用(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);
}
}
看了简单的定义之后,我们结合着代码来测试一下,强引用就不用说了,软引用的描述也很清楚,关键是 “弱引用” 与 “虚引用”。
弱引用:
由于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队列中。
虚引用:
同样,当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,而弱引用与虚引用呢?其实用处也很大,首先我们来看看弱引用,举个例子:
所有我添加进 registeredObjects 中的object永远不会被GC回收,因为这里有个强引用保存在registeredObjects里,另一方面如果我把代码改为如下:
现在如果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.WeakReferencejava.util.WeakHashMap虚引用让你可以清理已经执行finalize方法,但是还没有回收内存的对象特殊清理finalize方法执行之后java.lang.ref.PhantomReference
Android中的缓存处理及异步加载图片类的封装
- 流量开销:对于客户端——服务器端应用,从远程获取图片算是经常要用的一个功能,而图片资源往往会消耗比较大的流量。
- 加载速度:如果应用中图片加载速度很慢的话,那么用户体验会非常糟糕。
- 那么如何处理好图片资源的获取和管理呢?异步下载+本地缓存
- 1. 服务器的压力大大减小;
- 2. 客户端的响应速度大大变快(用户体验好);
- 3. 客户端的数据加载出错情况大大较少,大大提高了应有的稳定性(用户体验好);
- 4. 一定程度上可以支持离线浏览(或者说为离线浏览提供了技术支持)。
- 1. 提供网络服务的应用;
- 2. 数据更新不需要实时更新,即便是允许3-5分钟的延迟也建议采用缓存机制;
- 3. 缓存的过期时间是可以接受的(不会因为缓存带来的好处,导致某些数据因为更新不及时而影响产品的形象等)
- 1.下载或加载的过程中容易导致阻塞;
- 大位图Bitmap对象是png格式的图片的30至100倍;
- 2.大位图在加载到ImageView控件前的解码过程;BitmapFactory.decodeFile()会有内存消耗。
- 1.命中率;
- 2.合理分配占用的空间;
- 3.合理的缓存层级。
下图为对象层次的引用
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;
}
}
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);
}
}
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;
}
}
}
- Java对象的4中引用类型
- Java 中对象引用的类型
- Java 对象的4种引用类型
- Java 对象的4种引用类型
- java对象的引用类型
- java对象引用的类型
- java中引用类型的变量和对象的区别
- 【Java】---java对象中的4中引用类型
- 对Java中引用、对象、基本类型等的理解
- Java/Android对象的四中引用类型 (对象的强、软、弱和虚引用)
- Java/Android对象的四中引用类型 (对象的强、软、弱和虚引用)
- java的4中对象引用方式
- Java对象的4种引用类型(转)
- Java对象的四种引用类型
- Java的四种对象引用类型
- Java四种对象的引用类型
- Java对象的四种引用类型
- java 中对象的引用
- GNU C的__attribute__机制
- 制作自己的HUD
- 网络请求服务器之HTTP状态码
- Linux 3.9.10内核编译错误:multiple (or no) load addresses: This is incompatible with uImages的解决
- 第十三周阅读程序-交通工具类(3)
- Java对象的4中引用类型
- 遍历DataTable内存数据的三种方法性能对比
- 享元模式
- HDU 2016 数据的交换输出
- 分形之美
- LeetCode 261. Graph Valid Tree
- su root 和su - root 的区别
- 第13周-阅读程序(2)
- 字体颜色对话框