title: Android: Mediaplayer keeps playing in background. How to stop it?
body: <p>I have developed an Android app, where the user can play a sound by clicking on a button, in a certain fragment. However, when you exit this fragment or close the app it keeps playing. How do I stop it if one exits the fragment or closes the app?</p>
  
  <p>This is how I play the sound:</p>
  
  <pre><code>public class PageFragment_Bon extends Fragment implements View.OnClickListener{
  
      public static final String ARG_PAGE = "ARG_PAGE";
  
      private int mPage;
      private Button start, stop, replay;
      private MediaPlayer mediaPlayer;
      int [] filer = new int[18];
  
  
      public static PageFragment_Bon newInstance(int page) {
          Bundle args = new Bundle();
          args.putInt(ARG_PAGE, page);
          PageFragment_Bon fragment = new PageFragment_Bon();
          fragment.setArguments(args);
          return fragment;
      }
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          mPage = getArguments().getInt(ARG_PAGE);
             }
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View view = inflater.inflate(R.layout.fragment_boenner, container, false);
  
          start = (Button) view.findViewById(R.id.start);
          start.setOnClickListener(this);
  
          stop = (Button) view.findViewById(R.id.stop);
          stop.setOnClickListener(this);
  
          replay = (Button) view.findViewById(R.id.replay);
          replay.setOnClickListener(this);
  
           if(filer[mPage] != 0){
              start.setVisibility(View.VISIBLE);
              stop.setVisibility(View.VISIBLE);
              replay.setVisibility(View.VISIBLE);
              mediaPlayer = MediaPlayer.create(getActivity().getBaseContext(), filer[mPage]);
          }
  
      @Override
      public void onClick(View v) {
  
          if(v == start){
              mediaPlayer.start();
          }
  
          else if(v == stop){
              mediaPlayer.pause();
          }
  
          else if(v == replay){
              mediaPlayer.seekTo(0);
              mediaPlayer.start();
          }
      }
  
      }
  </code></pre>