Search code examples
androidandroid-mediaplayer

How to stop the media player properly


How do I stop the media player in fragment activity with pageradapter when the user clicks on the back button?

Every time I click the back button, the audio is still playing.

package com.androidbasedcollectionofstories;

import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class BRUSH1 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
{
        // TODO Auto-generated method stub
        View view =inflater.inflate(R.layout.brushing1,container,false);
        ImageView imageview = (ImageView) view.findViewById (R.id.imageView1);
        if(imageview == null) throw new AssertionError();
        imageview.setBackgroundResource(R.drawable.animbrushing1);
        AnimationDrawable anim = (AnimationDrawable)imageview.getBackground();
        anim.start();

        final MediaPlayer sound=MediaPlayer.create(getActivity(), R.raw.brushingtitle);
        sound.start();
        return view;
    }

}

Solution

  • If you need to stop media player, then you can stop in onDestroyView method.

    public class BRUSH1 extends Fragment {
    
        MediaPlayer sound;
    
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            View view =inflater.inflate(R.layout.brushing1,container,false);
            ImageView imageview = (ImageView) view.findViewById (R.id.imageView1);
            if(imageview == null) throw new AssertionError();
            imageview.setBackgroundResource(R.drawable.animbrushing1);
            AnimationDrawable anim = (AnimationDrawable)imageview.getBackground();
            anim.start();
    
            sound = MediaPlayer.create(getActivity(), R.raw.brushingtitle);
            sound.start();
            return view;
        }
    
        @Override
        public void onDestroyView() {
            if (sound != null) {
                sound.stop();
                sound.release();
            }
            super.onDestroyView();
        }
    
    }