由於內存不足(在程序中,而不是程序員),我一直在發生應用程序崩潰。 MAT表明,我的Activity的副本有時會在屏幕旋轉中保留,唯一保留僞造副本的對象是每個實例的TextToSpeech對象。我可以用這個片段複製此行爲:取向的變化TextToSpeech和內存泄漏
public class MainActivity extends Activity {
TextToSpeech mTts;
char[] mBigChunk = new char[1000000]; // not used; just makes MainActivity instances easier to see in MAT
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onStart() {
super.onStart();
if (mTts==null) // shouldn't be necessary and doesn't make any difference
mTts = new TextToSpeech(this, null); // commenting this out fixes the leak
}
@Override
public void onStop() {
super.onStop();
if (mTts != null) {
mTts.shutdown();
mTts = null; // shouldn't be necessary and doesn't make any difference
}
}
}
30後,一個和net.catplace.tts_leak.MainActivity的八個實例,以及各種TTS對象的多個實例之間MAT名單;例如:
Class Name | Shallow Heap | Retained Heap | Percentage
------------------------------------------------------------------------------------------------------------------
android.speech.* | | |
android.speech.tts.TextToSpeech$Connection$1 @ 0x42de94c8 Native Stack| 24 | 2,052,664 | 11.85%
android.speech.tts.TextToSpeech$Connection$1 @ 0x431dd500 Native Stack| 24 | 2,052,664 | 11.85%
android.speech.tts.TextToSpeech$Connection$1 @ 0x435cc438 Native Stack| 24 | 552 | 0.00%
android.speech.tts.TextToSpeech$Connection @ 0x441b3698 | 32 | 528 | 0.00%
android.speech.tts.TextToSpeech @ 0x43fb3c00 | 64 | 496 | 0.00%
android.speech.tts.TextToSpeech$Connection @ 0x43fb4420 | 32 | 48 | 0.00%
android.speech.tts.TextToSpeech$Connection$1 @ 0x43fb4440 Native Stack| 24 | 24 | 0.00%
android.speech.tts.TextToSpeech$Connection$1 @ 0x441b36b8 Native Stack| 24 | 24 | 0.00%
Total: 8 entries (13,079 filtered) | | |
------------------------------------------------------------------------------------------------------------------
MAT表示MainActivity的虛假副本被保留TTS:
Class Name | Shallow Heap | Retained Heap
---------------------------------------------------------------------------------------------------------------------
| |
net.catplace.tts_leak.MainActivity @ 0x437c6068 | 200 | 2,001,352
'- mContext android.speech.tts.TextToSpeech @ 0x431de6d8 | 64 | 496
'- this$0 android.speech.tts.TextToSpeech$Connection @ 0x441b3698 | 32 | 528
'- this$1 android.speech.tts.TextToSpeech$Connection$1 @ 0x441b36b8 Native Stack| 24 | 24
---------------------------------------------------------------------------------------------------------------------
我在一系列真實設備和自動真空澱積的得到這個水煤漿。上述結果是從的Nexus 7
我已經嘗試了不同的TTS引擎,使用不同的事件來創建和銷燬MTTS等
我的假設是,文字轉語音並不總是空的參考創建它的上下文,導致上下文(Activity)的泄露副本。但我是新來的;有什麼我做錯了嗎?
如果文字轉語音對象通過使構成'getApplicationContext()'而不是'this'(活動),問題似乎沒有發生。這種方法很有意義,因爲應用程序在方向更改時不會被破壞。然而,應該沒有必要這樣做。 –
我有同樣的問題。屏幕旋轉導致我的活動被泄漏。在內存中旋轉10次,10次活動。我改變它將getApplicationContext()傳遞給TextToSpeech對象,而不是像Peter建議的那樣傳遞給TextToSpeech對象,並解決了問題。繁榮! –