简体   繁体   中英

Android mediaPlayer not being correctly released

I'm trying to play a sound in an android widget on a button click, this is my current code:

@Override
public void onReceive(Context context, Intent intent) {
    Boolean hasToPlayMedia = false;
    MediaPlayer mediaPlayer = new MediaPlayer();
    if (intent.getAction().equals("somevalue")) {
        mediaPlayer = MediaPlayer.create(context, R.raw.somevalue);
        hasToPlayMedia = true;
    // OTher conditionals here
    }
    if (hasToPlayMedia) {
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.start();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                mp.reset();
                mp.release();
                mp = null;
            }
        });
    }
    super.onReceive(context, intent);
}

However, in the console I read:

E/MediaPlayer﹕ Should have subtitle controller already set
W/MediaPlayer-JNI﹕ MediaPlayer finalized without being released

and sometimes after a while clicking the button doesn't play the sound.

You have to keep a static reference to your MediaPlayer inside your class and outside the method scope. Otherwise, the OS may clean its resources and then when you try to access it from inside the onCompletion() method, it will be in an illegal state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM