I’ve tried the following:
Activity a = getActivity();
a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Thread.sleep(2000);
a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Thread.sleep(2000);
on Android emulator. But it doesn’t behave quite the same way as pressing Ctrl+F11 to rotate the screen manually.
So what is the correct way to change the orientation programmatically?
This should be the right way to do it. It’s your test that’s broken.
First of all, don’t use
Thread.sleep, it’ll freeze your entire App and will prevent anything from happening (including the orientation change). Try to use a Handler instead.Secondly, the change will most likely not happen immediately, but only after you left
onCreate()(and propably a couple of other lifecycle methods).Thirdly, if you change orientation your Activity will be destroyed and recreated. So you can’t really switch back and forth within a single Activity instance.