5

I have an activity with a media player as a member variable.

My media player is initialized like this:

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

Everything works just fine, and then i override my activity onStop method to release the Media Player.

if(mMediaPlayer!=null){
   if(mMediaPlayer.isPlaying()){
       mMediaPlayer.stop();
   }
   mMediaPlayer.release();
   mMediaPlayer=null;
}

But after the activity has stopped i get a memory leak report from LeakCanary.

The report is like this:

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.

Yes i have a MyApp class which extends Application and i am holding a reference to MyApp instance in a static field, but i never use that reference in my activity, how can i solve this leak ?

[EDIT]

Here is the code of my Activity:

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();
        }

    }



   }

 }
4

1 回答 1

4

在我的测试中,我发现这发生在 HTTP 流传输期间。

当我在目标上检查 MediaPlayer 的源代码时(在我的情况下为 API19),确实有一个 StreamProxy 实例正在设置和分配,但没有在release方法中释放,而只是在reset方法中。

这对我有用:

if (mediaPlayer != null) {
    mediaPlayer.reset();
    mediaPlayer.release();
    mediaPlayer = null;
}
于 2015-11-24T02:15:38.797 回答