Sunday, March 11, 2012

Lights-out mode in Android

As I noted in the last post, Google and players like it when you use the "lights out" option to hide the status bar during games. I spent a couple hours today figuring out how to do that.

1) Wrap all of this code in a check to see if we are on Android 3 or higher so we can still run on 2.3.

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {

2) Find the right view. We create a GLView in our startup code, so this part is easy for us. Otherwise you'd want to add an android id to the top view in the layout file, and then use findViewById to find it.

(in layout definition) android:id="@+id/RootView"
(in startup code) View root=findViewById(R.id.RootView);

3) Toggle the visibility flag to SYSTEM_UI_FLAG_LOW_PROFILE

view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);

4) Set up a visibility listener to re-hide the menu bar after a delay when it becomes visible again. Otherwise when you touch the bar it will stay visible forever. We add the delay in because things go wonky if you rehide in the unhide notification.

view.setOnSystemUiVisibilityChangeListener(

new View.OnSystemUiVisibilityChangeListener()

{

public void onSystemUiVisibilityChange(int visibility)

{

if (visibility == 0)

{

Runnable rehideRunnable = new Runnable()

{

public void run() {

view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);

}

};

Handler rehideHandler = new Handler();

rehideHandler.postDelayed(rehideRunnable, 2000);

}

}

});

2 comments:

  1. Can you use android.os.Build.VERSION_CODES.HONEYCOMB and setSystemUiVisibility in an Android 2.3.x project without getting any warnings or error messages?

    ReplyDelete
  2. You need to have honeycomb or ICS as your target sdk, then 2.3 or whatever as your min sdk. We still support 2.2 and no one has complained that the app isn't working. The call to setsystemuivisibility has to be avoided at runtime on older android versions though.

    ReplyDelete