简体   繁体   English

如何在Android游戏中释放/释放内存

[英]How to deallocate/free memory in android game

I created a 2d game for android using Bitmaps. 我使用Bitmaps为Android创建了一款2D游戏。 After closing the game, android studio memory section shows that the memory is not de-allocated. 关闭游戏后,android studio内存部分显示内存未解除分配。 So how can i de-allocate memory which is allocated for bitmaps. 那么如何解除分配给位图的内存。 I have a Bitmap array called chopper and i am initializing like 我有一个名为chopper的Bitmap数组,我正在初始化

    chopper[0] = BitmapFactory.decodeResource(getResources(), R.drawable.copter1);
    chopper[1] = BitmapFactory.decodeResource(getResources(), R.drawable.copter2);
    chopper[2] = BitmapFactory.decodeResource(getResources(), R.drawable.copter3);

So during closing the game i tried to free memory like 因此,在关闭游戏时,我试图释放内存

chopper[0]=null;

But it doesn't show free memory in android studio memory graph. 但它没有显示android studio内存图中的空闲内存。 Is it the way to free memory? 是免费记忆的方式吗? If not how can i free the memory before closing the game. 如果不是,我怎么能在关闭游戏之前释放内存。 Thanks in advance 提前致谢

In Java, making a object null will not release the memory. 在Java中,使对象为null将不会释放内存。 The memory might be released by the garbage collector when the garbage collector runs next time if are no references to that object anywhere. 如果垃圾收集器下次运行,如果在任何地方都没有引用该对象,则垃圾收集器可能会释放内存。

In your case, assuming you are using this array in a activity, close all the resources that might be using this array in the onDestroy() method of your activity, and ensure there are no objects floating around that refers this object after the Activity is destroyed. 在您的情况下,假设您在活动中使用此数组,请关闭可能在活动的onDestroy()方法中使用此数组的所有资源,并确保在Activity之后没有任何浮动的对象引用此对象销毁。

You have to call bitmap.recycle() API to actually free memory. 您必须调用bitmap.recycle() API才能实际释放内存。 See official article about bitmaps memory management 请参阅有关位图内存管理的官方文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM