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()方法上幫助併發布位圖。因此,只要活動失焦,您就可以釋放內存。