How to capture screen off on android

I was wondering if there is a way to capture if the screen is turned off during game play on an android device. I would like to activate the pause menu in my game when this happens. Its there a way to capture the onPause() method from android or can it be done with something like app.pause == true



Thanks

I would guess this would trigger the onLostFocus event of SimpleApplication? (don’t quote me on this). Try this inside your SimpleApplication class:



[java]@Override

public void gainFocus() {

// Do nothing

}



@Override

public void loseFocus() {

// Add pause menu

}[/java]

1 Like

That doesn’t seem to work. Any other ideas?



Thanks

There is an onPause method in the android Activity.

I guess in the onPause you can call w/e method you want from you application.

Don’t forget to call the super.onPause() though.

gainFocus and loseFocus are currently not tied into onPause and onResume on the Android side. It should be, but I haven’t had time to integrate it yet.



In the meantime, in MainActivity, do the following:



[java]

@Override

protected void onPause() {

loseFocus();

super.onPause();

}



@Override

protected void onResume() {

super.onResume();

gainFocus();

}

[/java]



Then in the main application:

[java]

@Override

public void gainFocus(){

logger.log(Level.INFO, “gainFocus”);

super.gainFocus();

// do something when the game gets focus back (ie. app is resumed from home screen)

}



@Override

public void loseFocus(){

logger.log(Level.INFO, “loseFocus”);

// do something when the game losing focus (ie. Home button pressed)

super.loseFocus();

}



[/java]

1 Like

iwgeric your way seems a lot cleaner and you don’t really have to modify the android main activity class. After importing my game pakage into the main activity class, I did this (see below). Note you can’t add images or models during this proccess. I got a warning about trying to invoke another thread over a current thread which crashed the app, but you can set a flag. which I handeld in the games main loop. Thanks for all the help.



[java]

@Override

protected void onPause() {

if(app != null)

if(app.getStateManager.getState(Pause.class) != null)

app.getStateManager.getState(Pause.class).activate();

super.onPause();

}[/java]

I just committed a change to nightly that calls the standard loseFocus and gainFocus methods when the Android onPause and onResume get called. After the next nightly build, you should be able to just put your code in these methods in the main application.

1 Like