由于内存不足(在程序中,而不是程序员中),我一直在发生应用程序崩溃。MAT 显示,我的 Activity 的副本有时会在屏幕旋转时保留,而唯一使虚假副本保持活动状态的对象是每个实例的 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 次方向更改后,MAT 列出了 1 到 8 个 net.catplace.tts_leak.MainActivity 实例,以及各种 TTS 对象的多个实例;例如:
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
---------------------------------------------------------------------------------------------------------------------
我在一系列真实设备和 AVD 中都得到了这种行为。以上结果来自 Nexus 7。
我尝试过不同的 TTS 引擎,使用不同的事件来创建和销毁 mTts 等。
我的假设是 TextToSpeech 并不总是将其对创建它的上下文的引用归零,从而导致上下文(活动)的泄漏副本。但我对此并不陌生;有什么我做错了吗?