1
votes

I have an android app where in my Main activity I can play music onCreate(), pause music onPause() and restart music onResume(). I am using MediaPlayer. The problem is that I don't want the music to restart onResume() when I'm rotating the screen on my Main activity. I only want the music to restart when I'm coming back to my Main activity from another activity. Any suggestions?

private MediaPlayer mp;

mp = MediaPlayer.create(MainActivity.this, R.raw.always_sunny); mp.setLooping(true); mp.start();

@Override
protected void onPause() {
  super.onPause();
  mp.getCurrentPosition();
  mp.pause();
}

@Override
protected void onResume() {
  super.onResume();
  mp.seekTo(0);
  mp.start();
}
1
The issue with the music is resolved, but now there is a new issue. I am using both portrait and landscape layout for my Main activity. I have it set up so that my portrait and landscape layout uses two different images for one of the ImageView in my layouts. Unfortunately for me, android:configChanges="orientation" also prevents the image from changing when the screen rotates to and from portrait to landscape. So how will I be able to change my ImageView image source on screen rotate, but also prevent the audio playing in my Main activity from restarting on screen rotate? - kimbaudi
Can I keep android:configChanges="orientation" in the AndroidManifest.xml and maybe programmatically check if the device is in portrait/landscape mode and set the image source that way? - kimbaudi

1 Answers

3
votes

Add the following attribute to the activity in the manifest:

android:configChanges="keyboardHidden|orientation|screenSize"

This would avoid that the activity restarts on orientation changes or when the keyboard appears.

If you need to do something when the rotation changes (for example, change an image in your case), add the following method to your activity:

@Override
public void onConfigurationChanged (Configuration newConfig) {
  // Change here your image
}