温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android的软应用的使用

发布时间:2020-07-24 14:20:09 来源:网络 阅读:454 作者:祝你幸福365 栏目:移动开发

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;
	}

}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI