0

我目前正在使用内存很少的使用Android 2.3.3的嵌入式设备。 图形用户界面使用了大量的位图,有时,我们看到一些OutOfMemory异常,这是由于Android没有足够好地处理位图内存以足够快地释放内存以使新活动正确启动。有效的方法来清理Android 2.3.3中的所有活动位图

确切的说,Android的官方文档(https://developer.android.com/training/displaying-bitmaps/manage-memory.html)告诉我们:

On Android 2.3.3 (API level 10) and lower, the backing pixel data for a bitmap is stored in native memory. It is separate from the bitmap itself, which is stored in the Dalvik heap. The pixel data in native memory is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash.

In Android 2.3.3 (API level 10) and lower, using recycle() is recommended. If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. The recycle() method allows an app to reclaim memory as soon as possible.

Caution: You should use recycle() only when you are sure that the bitmap is no longer being used. If you call recycle() and later attempt to draw the bitmap, you will get the error: "Canvas: trying to use a recycled bitmap".

于是我开始实现一些回收()中的onDestroy(),但我面对不同的问题:

- onDestroy()不可靠,因为我们无法确定Android会在完全终止应用程序之前调用它。所以,即使它看起来是清理位图的好地方,也可能会发生一个活动在另一个活动开始时立即死亡,并且无法为其自己的位图分配内存。

  • 会有更好的地方来实现位图回收?

- 有些绘图是通过Java代码声明的,那些绘图很容易回收,因为我们可以保留对它们的引用。但是通过Xml声明呢?

  • 有没有办法找到视图的所有BitmapDrawable(不看全视图树)?
  • Android如何管理XML声明的可绘制?是否只有一个java对象/ xml对象? (这意味着如果在多个视图/活动中使用xml引用,则可能会遇到一些问题) 每个对象只有一个实例会大大减少使用的内存,但需要更多的逻辑才能正确清理。

这些具体问题导致的主要问题: 如何处理位图,以确保在另一个之前的onCreate(),我们清理以前的活动的每一个位图?

谢谢!

回答

0

您可以使用finalize()执行某些任务的方法。
这样,您可以仔细检查内存是否被释放。

Finalize()
finalize() method is a protected and non-static method of java.lang.Object class. This method will be available in all objects you create in java. This method is used to perform some final operations or clean up operations on an object before it is removed from the memory. you can override the finalize() method to keep those operations you want to perform before an object is destroyed. Here is the general form of finalize() method.

例如

 @Override 
     protected void finalize() throws Throwable 
     { 
       System.out.println("From Finalize Method"); 
      } 

的另一种方式
实施的另一方式是通过downsampling和位图的caching。如果缓存有效,那么您可以在onstart()和onStop()方法上帮助并发布位图。因此,只要活动失焦,您就可以释放内存。