我的简单android活动如何泄漏内存?

时间:2011-10-01 07:32:39

标签: android memory-leaks

我的活动只显示一张图片:

public class PhotoFrameActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        File externalStorageDir = Environment.getExternalStorageDirectory();
        File picturesDir = new File(externalStorageDir, "DCIM/Camera");
        File[] files = picturesDir.listFiles(new FilenameFilter(){
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".jpg");
            }});
        List<File> photoFiles = Arrays.asList(files);
        if (!photoFiles.isEmpty()) {
            try {
                Bitmap currentPhoto = BitmapFactory.decodeStream(new FileInputStream(photoFiles.get(3)));
                ImageView view = (ImageView) findViewById(R.id.photo);
                view.setImageBitmap(currentPhoto);
            } catch (FileNotFoundException e) {
                Log.e("SHOWPIC", "Could not find photo", e);
            }
        }
    }

}

如果重新启动活动,则不会回收内存。即如果我把手机翻了两次,我会得到以下的FC:

10-01 17:29:06.011: ERROR/AndroidRuntime(8446): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
10-01 17:29:06.011: ERROR/AndroidRuntime(8446):     at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
10-01 17:29:06.011: ERROR/AndroidRuntime(8446):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:470)
10-01 17:29:06.011: ERROR/AndroidRuntime(8446):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:525)
10-01 17:29:06.011: ERROR/AndroidRuntime(8446):     at net.badgerhunt.photoframe.PhotoFrameActivity.onCreate(PhotoFrameActivity.java:34)

我如何泄漏?

3 个答案:

答案 0 :(得分:3)

当图像大小较大时,会发生内存不足异常。您必须在解码流时在选项中定义样本大小。喜欢

BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap preview_bitmap=BitmapFactory.decodeStream(is,null,options);

请查看以下链接以获取更多信息。

Strange out of memory issue while loading an image to a Bitmap object

答案 1 :(得分:3)

正如Yashwanth Kumar所说,这不是因为你的形象太大了。即使您减小样本量,您仍将(最终)获得OOM。您所拥有的内存泄漏将无法通过减少样本大小来解决。

好像你有内存泄漏。您可以进行内存泄漏搜索并尝试找到问题的根源,或者您可以覆盖活动的ondestroy方法并执行

 @Override
    protected void onDestroy() {
        super.onDestroy();
    view.setImageBitmap(null);
    currentPhoto.recycle();
    }

这将确保您的位图得到回收,并在您的活动被销毁时释放内存(如方向切换的情况)。不过,我建议你观看这段视频,最终找到泄漏的根源:http://www.google.com/events/io/2011/sessions/memory-management-for-android-apps.html

答案 2 :(得分:0)

我不认为是这种情况(对于Android设备,您的图片必须非常大),但为什么不尝试关闭此流?

Bitmap currentPhoto = BitmapFactory.decodeStream(new FileInputStream(photoFiles.get(3)));