gpt4 book ai didi

android - 我的简单 android Activity 如何泄漏内存?

转载 作者:太空狗 更新时间:2023-10-29 16:23:43 26 4
gpt4 key购买 nike

我的 Activity 只显示一张图片:

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

}

如果 Activity 重新启动,则不会回收内存。即,如果我转动手机两次,我会得到以下 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)

我怎么漏水了?

最佳答案

正如 Yashwanth Kumar 所建议的,这不是因为您的图像太大。即使您减少样本量,您仍然(最终)会得到 OOM。您的内存泄漏不会通过减少样本量来解决。

您似乎有内存泄漏。您可以继续寻找内存泄漏并尝试找到问题的根源,或者您可以覆盖 Activity 的 ondestroy 方法并执行

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

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

关于android - 我的简单 android Activity 如何泄漏内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7618886/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com