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

来源:互联网 发布:php获取百度统计数据 编辑:程序博客网 时间:2024/04/29 18:50

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


原创粉丝点击