Search code examples
androidorientationlockscreen

Prevent restarting landscape Android application on lock


I am developing a game (sort of) which uses OpenGL and has background music. Application runs only in landscape mode.

Problem I have, happens when user locks screen. At that point onStop() is called, screen orientation is changed and soon after my Activity is restarted as a result of orientation change. This means OpenGL surface is recreated, music starts playing again and all sorts of other things. This is counter-intuitive as locking screen should suspend CPU intensive operations, not start them.

Adding android:configChanges="orientation" to manifest did nothing. I do realize that I am probably missing screenSize in android:configChanges but I can not add it since I am targeting earlier API versions which do not have this option available.

So, question is: What's the proper way to handle this? On which event should I initialize my application so that everything works as expected?


Solution

  • Adding screenSize to configChanges in manifest doesn't mean that your program won't run on older version. You just need to set targetSdkVersion to higher version and minSdkVersion to whatever you like. In intelljIDEA I set ModuleSKD to 4 in Project Structure so it doesn't highlight screenSize as invalid. It must be similar in Eclipse.

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" />
    
    <activity android:name=".MyActivity"
          android:label="@string/app_name"
          android:configChanges="orientation|screenSize|keyboard|keyboardHidden|navigation">
    

    Also you can check the version in code like this:

    if (Build.VERSION.SDK_INT >= 11) 
    

    This way your app work on 2.2 as well as higher versions.

    I think you won't need onConfigurationChanged because your game probably run only in landscape mode but if your interested have a look at my question very similar to yours and my own answer.

    replace layout on orientation change