Orientation In Android

Recently I've been exploring the Android operating system. I was sufficiently curious to purchase an ADP1 (an android based developer phone from Google). I think I've done enough research to begin porting my M12 puzzle. I thought I'd share some of the things I've learned along the way starting with the way orientation works.

Both the T-Mobile G1 and the ADP1 allow applications to be displayed with two different orientations - landscape and portrait. By default the the orientation is controlled by whether the keyboard is exposed. The application can override the default orientation behavior, but doing so requires an understanding of the way orientation works in Android.

Transitions between portrait and landscape mode result in a new instances of of the Activity and each View. Since the user expects the display to retain it's state other than rotating the standard Activity.onSaveInstanceState() and Activity.onCreate() methods save and restore data to the Bundle such that the state of each View is restored. So, if you override those methods make sure you start by calling the default using super in order to allow each View's state to be retained. This only moderately related to what I really wanted to talk about, but it's interesting.

Since my M12 puzzle is relatively wide landscape mode works best for it. Consequently I want to override the default behavior of of switching to portrait mode when the keyboard is retracted. Also, I'd like to pop up something like a message the first time the phone is in a state that would normally cause an application to be in portrait mode, but I don't want to keep bothering the user. Here's some code that can be placed into the onCreate() that accomplishes this:

// Query what the orientation currently really is.
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
    // The following message is only displayed once.
            "This application works best in landscape mode.",
    // The value set by the following is initially
    // ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED. Once set it
    // retains it's value. The View will be rendered in the specified
    // orientation from this point forward.

blog posts: