Home > Software design >  How to stop playing audio when screen oreitation is change in Android
How to stop playing audio when screen oreitation is change in Android

Time:11-07

I want to set a autoplay sound and it only play once, no matter the rotation is. I was trying to make my Mediaplayer in the onCreate of Mainactivity. And when I try to rotate the screen, the audio continued to play.

I try a different method like set up a subclass and call in the activity instead of puting it in onCreat of MainActivity to make it only play once and ignore doing rotate, but it still doesn't work, can someone explain to me how can I fix it? Thank you!

CodePudding user response:

You should clerify your case with code, but seams that it should help

override fun onStop() {
    super.onStop()
    player?.release()
    player = null
}

CodePudding user response:

You should use onConfigurationChanged to make this work.

in your manifest file add this to your activiy

 android:configChanges="orientation|keyboardHidden"
<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:exported="true">

In your MainActiviy code implement this method:

@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // check weather the player is null
    if(player == null) return;
    player.stop();
   
}
  • Related