decodeResource(Resource res ,int id)与OutofMemory错及解决办法

  我在做关于Android 的Bitmap的小实验时发现用decodeResource(Resource res ,int id)方法去解析,创建Bitmap对象时报OutofMemory错误。原因是模拟器的内存是比较小的,如过程序在不停地解析,创建Bitmap对象,可能前面的创建的Bitmap所占用的内存还没有回收而引发了OutofMemory错误。所以我们可以用Android提供的boolean isRecycled():返回该bitmap对象是否被回收。 void recycle():强制回收来回收自己。

下面以一个例子来说明一下


public class BitmapTest extends Activity
{
	String[] images = null;
	AssetManager assets = null;
	int currentImg = 0;
	ImageView image;
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		image = (ImageView)findViewById(R.id.image);
		try
		{
			assets = getAssets();
			//获取/assets/目录下所有文件
			images = assets.list("");
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		//获取bn按钮
		final Button next = (Button)findViewById(R.id.next);
		//为bn按钮绑定事件监听器,该监听器将会查看下一张图片
		next.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View sources)
			{
				//如果发生数组越界
				if (currentImg >= images.length)
				{
					currentImg = 0;
				}
				//找到下一个图片文件
				while (!images[currentImg].endsWith(".png")
					&& !images[currentImg].endsWith(".jpg")
					&& !images[currentImg].endsWith(".gif"));
				{
					currentImg++;
					//如果已发生数组越界
					if (currentImg >= images.length)
					{
						currentImg = 0;
					}
				}
				InputStream assetFile = null;
				try
				{
					//打开指定资源对应的输入流
					assetFile = assets
						.open(images[currentImg++]);
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
				BitmapDrawable bitmapDrawable = (BitmapDrawable) image
					.getDrawable();
				//如果图片还未回收,先强制回收该图片
				if (bitmapDrawable != null
					&& !bitmapDrawable.getBitmap().isRecycled())             
				{
					bitmapDrawable.getBitmap().recycle();
				}
				//改变ImageView显示的图片
				image.setImageBitmap(BitmapFactory.decodeStream(assetFile)); 
			}
		});
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值