我在做关于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));
}
});
}
}