Java中的SoftReference
即對象的軟引用。如果一個對象具有軟引用,內存空間足夠,垃圾回收器就不會回收它;如果內存空間不足了,就會回收這些對象的內存。只要垃圾回收器沒有回收它,該對象就可以被程序使用。軟引用可用來實現內存敏感的高速緩存。使用軟引用能防止內存泄露,增強程序的健壯性。
SoftReference的特點是它的一個實例保存對一個Java對象的軟引用,該軟引用的存在不妨礙垃圾收集線程對該Java對象的回收。也就是說,一旦SoftReference保存了對一個Java對象的軟引用后,在垃圾線程對這個Java對象回收前,SoftReference類所提供的get()方法返回Java對象的強引用。另外,一旦垃圾線程回收該Java對象之后,get()方法將返回null
用Map集合緩存軟引用的Bitmap對象
Map<String, SoftReference<Bitmap>> p_w_picpathCache = new new HashMap<String, SoftReference<Bitmap>>();
//強引用的Bitmap對象
Bitmap bitmap = BitmapFactory.decodeStream(InputStream);
//軟引用的Bitmap對象
SoftReference<Bitmap> bitmapcache = new SoftReference<Bitmap>(bitmap);
//添加該對象到Map中使其緩存
p_w_picpathCache.put("1",softRbitmap);
..
.
//從緩存中取軟引用的Bitmap對象
SoftReference<Bitmap> bitmapcache_ = p_w_picpathCache.get("1");
//取出Bitmap對象,如果由于內存不足Bitmap被回收,將取得空
Bitmap bitmap_ = bitmapcache_.get();
如果程序中需要從網上加載大量的圖片 這時就考慮采用在sdcard上建立臨時文件夾緩存這些圖片了
package com.minimax.softreferencedemo;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Map<String, SoftReference<Bitmap>> p_w_picpathCache=new HashMap<String, SoftReference<Bitmap>>();
Bitmap bitMap=BitmapFactory.decodeResource(getResources(), R.drawable.aidegenyuan);
SoftReference<Bitmap> value=new SoftReference<Bitmap>(bitMap);
p_w_picpathCache.put("yongyuanzaiyiqi", value);
//使用p_w_picpathCache
SoftReference<Bitmap> soft=p_w_picpathCache.get("yongyuanzaiyiqi");
Bitmap bitMap2=soft.get();
ImageView p_w_picpathView=(ImageView) findViewById(R.id.p_w_picpathview);
p_w_picpathView.setImageBitmap(bitMap2);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。