Set emulator/device orientation programmatically i

2019-04-08 00:46发布

问题:

In my instrumentation tests I want to test something in both landscape and portrait mode, so I'd like to set the orientation before the tests start. Is there a way to set the device or emulator orientation programmatically?

I am aware of the setRequestedOrientation() method but this works for a certain activity, if another activity is started I have to remember to call it again. What I'm looking for is a way to set the orientation "globally", so that every new activity is automatically started with that orientation.

UPDATE:

The solution must fit 2 requirements: 1) it doesn't make me change my production code, 2) it needs to run in a CI environment.

回答1:

Here is a ViewAction I created for making this simpler: https://gist.github.com/nbarraille/03e8910dc1d415ed9740

The usage is described in the comments. Hope that helps.



回答2:

You can do it for all of your activities by making a own AbtractActivity Class.

public abstract class AbstractActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
}

Now you have to inherit all your activities from this class.



回答3:

You can start two emulator simultaneously one in potrait mode and one in landscape mode. To change emulator orientation use ctrl + f12.