How to stop audio from playing when back button is pressed?

后端 未结 3 1709
日久生厌
日久生厌 2021-01-16 11:26

Hi all here is my code:

   final ImageView imageView = (ImageView) findViewById(R.id.Image7);
   imageView.setImageResource(mFullSizeIds[position]);
   image         


        
相关标签:
3条回答
  • 2021-01-16 11:58

    Override the onBackPressed method, and stop your MediaPlayer object, which is mp.

    0 讨论(0)
  • 2021-01-16 12:04

    Add

       @Override
        public void onBackPressed ()
        {
          if (mp != null)
            mp.stop();
          super.onBackPressed();
        }
    

    and

    @Override
    public void onPause ()
    {
      if (mp != null)
      {
        mp.pause();
        mp.stop();
      }
      super.onPause();
    }
    
    0 讨论(0)
  • 2021-01-16 12:21

    Create an onStop in the activity and make mp a class variable although I always create/prefer media player helper class for this sort of stuff. Then call mp.stop()/pause on onStop.

    private MediaPlayer mp = null;
    
    @Override
    public void onStop() {
        super.onStop();
    
        if (mp != null) {
            mp.stop();
        }
    }
    

    then you just create it with removing the MediaPlayer before mp:

    mp = MediaPlayer.create(Audio.this,mAudio[position]);
    
    0 讨论(0)
提交回复
热议问题