I am having a problem in screen orienation in my application. I created an alternate layout in res/layout-lan folder for landscape mode. The problem occurred during orientation
v
Create Folder res/layout-land
Instead of res/layout-lan <---- put here d in folder-name
1.An activity get recreated without destroying the old activity.
The recreation of the Activity
is the natural default behavior of Android when a configuration change occurs. The likely reason your old Activity lingers in memory is because it is referencing a currently playing instance of a MediaPlayer
.
Because you are using different layout resources for landscape and portrait, it is to your advantage to let Android recreate the Activity and pull the appropriate resources each time. If you handle rotation yourself, you will be responsible to reloading the proper layout as well.
2.since i am using mediaplayer in my app,on screen rotation the .mp3 is playing on both orientation concurrently..
There are two solutions to this issue...
The ideal solution is to move your media playback into a Service
. The Activity
can call the Service
to start/stop/etc. playback when directed by the user, but putting this into a background component like a Service
allows it to operate continuously even when your Activity
is in flux due to the changes. This is the design pattern the Android team encourages, where your Activity
really only deals with user interface.
Another workable solution is to pass your MediaPlayer
from the old Activity
to the new one using onRetainNonConfigurationInstance()
. This allows the single MediaPlayer
to exist between Activity
instances, keeping the playback consistent. For example:
public class MyActivity extends Activity {
private MediaPlayer mPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Check if we have a player passed in from the last instance
mPlayer = (MediaPlayer)getLastNonConfigurationInstance();
//If not, make a new one
if (mPlayer == null) {
mPlayer = new MediaPlayer();
//...Set up new player instance...
}
}
@Override
public Object onRetainNonConfigurationInstance() {
//Clear our member variable to guarantee this Activity
// is allowed to GC after onDestroy()
MediaPlayer instance = mPlayer;
mPlayer = null;
//Hand our current player up to the next Activity to be created
return instance;
}
}
Another option to ensure the best memory cleanup would be to define mPlayer
as a WeakReference<MediaPlayer>
to allow the GC to claim the old Activity
, even if the MediaPlayer
is playing audio at the time of the configuration change.
you can stop recreation of activity when Screen orientation changed by below steps.
set configChanges tag as below
<activity android:name=".Activity_name"
android:configChanges="orientation|keyboardHidden">
use below method.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// to do on orientation changed
}
}