我有一个媒体播放器作为成员变量的活动.
我的媒体播放器初始化如下:
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setDataSource(MyActivity.this, URL);
mMediaPlayer.prepareAsync();
//i set a on Prepared Listener to start playing on Prepared
一切正常,然后我覆盖我的活动onStop方法以发布Media Player.
if(mMediaPlayer!=null){
if(mMediaPlayer.isPlaying()){
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer=null;
}
但是在活动停止后,我从LeakCanary收到了内存泄漏报告.
该报告是这样的:
MyApp.Instance->
MyApp.mLoadedApk->
LoadedApk.mReceivers->
ArrayMap.mArray->
arrayObject[].[3]->
ArrayMap.mArray->
arrayObject[][0]->
MediaPlayer.mProxyReceiver->
MediaPlayer.mProxyContext->
leaks MyActivity instance.
MyApp.Instance->
MyApp.mLoadedApk->
LoadedApk.mReceivers->
ArrayMap.mArray->
arrayObject[].[3]->
ArrayMap.mArray->
arrayObject[][0]->
MediaPlayer.mProxyReceiver->
MediaPlayer.mProxyContext->
leaks MyActivity instance.
是的,我有一个扩展应用程序的MyApp类,并且在静态字段中持有对MyApp实例的引用,但是我从未在活动中使用该引用,如何解决此泄漏?
[编辑]
这是我的活动代码:
public class PlayActivity extends ActionBarActivity {
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onStop() {
super.onStop();
if(mediaPlayer!=null){
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer=null;
}
}
public void playIt(View view){
if(mediaPlayer==null){
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
if(!mediaPlayer.isPlaying()){
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(PlayActivity.this, Uri.parse("http://www.noiseaddicts.com/samples_1w72b820/142.mp3"));
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
解决方法:
在测试期间,我发现这是在HTTP流传输期间发生的.
当我检查目标上的MediaPlayer的源代码(在我的示例中为API19)时,确实存在一个StreamProxy实例正在设置和分配,但没有在release方法中释放,而仅在reset方法中释放.
这为我工作:
if (mediaPlayer != null) {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
}