2015-07-10 30 views
1

當我用AndroidDeviceMonitor調試我的應用時,發現我的應用堆很奇怪。啓動應用程序(SplashActivity - > MainActivity)後,「1字節數組」分配了42MB。我確信SplashActivity已被破壞,我正在使用LeakCanary來發現是否有任何內存泄漏。但我沒有找到任何東西。Android第一次活動沒有真正銷燬

然後我嘗試在沒有任何其他代碼的情況下創建一個新的SplashActiviy,只需setContentViewonCreate()方法。

佈局XML是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:layout_gravity="center" 
android:gravity="center"> 
<ImageView 
    android:id="@+id/splash" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:scaleType="fitXY" 
    android:src="@drawable/splash2"/> 
<ImageView 
    android:id="@+id/logo" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerInParent="true" 
    android:scaleType="fitCenter" 
    android:src="@drawable/splashlogo"/> 
</RelativeLayout> 

我再次調試和 「1字節數組」 仍然是42MB。然後,我嘗試從我的佈局中刪除src標記。 「1字節數組」減少到35MB。所以,我想問題是圖像資源沒有被回收。任何人都可以告訴我更多關於第一次啓動活動的細節。爲什麼它不釋放這些資源?

+0

我可以看到您用來啓動MainActivity的意圖嗎? – Eoin

+0

Intent intent = new Intent(this,MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK \t \t \t \t \t \t | Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent); this.finish(); 也tryed刪除這些標誌,得到了相同的結果@ Modge –

+0

當你在主要活動中按下後退按鈕,啓動畫面沒有了嗎? – Eoin

回答

0

如何確保imge圖像被釋放以進行垃圾回收可以在onStop中將圖像設置爲null,以確保沒有任何內容引用它。

@Override 
public void onStop() { 
    super.onStop(); 

    mImageView.setImageDrawable(null); 
} 

然後,您可以使用AndroidDeviceMonitor強制執行垃圾回收以確保它從堆中釋放。

+0

是的,我試過了。它真的從堆中釋放出來,但我很好奇。爲什麼在完成SplashActivity後,這些內存沒有被釋放。我總是需要像'mImageView.setImageDrawable(null);'? –

+0

這可能是多種原因。 SplashActivity沒有真正完成,或者您在應用程序中的其他地方使用該圖像,並繼續參考它。 – Eoin

+0

此外,隨着Java垃圾收集它不會一直清除內存。它只會在JVM認爲需要基於Java堆大小的垃圾回收時觸發。 閱讀更多:http://javarevisited.blogspot.com/2011/04/garbage-collection-in-java.html#ixzz3fTEn3RhT – Eoin