溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android的軟應(yīng)用的使用

發(fā)布時間:2020-07-24 14:20:09 來源:網(wǎng)絡(luò) 閱讀:467 作者:祝你幸福365 欄目:移動開發(fā)

Java中的SoftReference
即對象的軟引用。如果一個對象具有軟引用,內(nèi)存空間足夠,垃圾回收器就不會回收它;如果內(nèi)存空間不足了,就會回收這些對象的內(nèi)存。只要垃圾回收器沒有回收它,該對象就可以被程序使用。軟引用可用來實(shí)現(xiàn)內(nèi)存敏感的高速緩存。使用軟引用能防止內(nèi)存泄露,增強(qiáng)程序的健壯性。   
SoftReference的特點(diǎn)是它的一個實(shí)例保存對一個Java對象的軟引用,該軟引用的存在不妨礙垃圾收集線程對該Java對象的回收。也就是說,一旦SoftReference保存了對一個Java對象的軟引用后,在垃圾線程對這個Java對象回收前,SoftReference類所提供的get()方法返回Java對象的強(qiáng)引用。另外,一旦垃圾線程回收該Java對象之后,get()方法將返回null

用Map集合緩存軟引用的Bitmap對象

Map<String, SoftReference<Bitmap>> p_w_picpathCache = new new HashMap<String, SoftReference<Bitmap>>();
//強(qiáng)引用的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對象,如果由于內(nèi)存不足Bitmap被回收,將取得空

Bitmap bitmap_ = bitmapcache_.get();

如果程序中需要從網(wǎng)上加載大量的圖片 這時就考慮采用在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;
	}

}


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI