Search code examples
javaandroidlibgdx

libgdx make android back button act like home button


I want the back button of an android device to act like the home button when pressed (pause the app and lose focus)

i have this :

(Gdx.input.setInputProcessor(this); and Gdx.input.setCatchBackKey(true); are called)

@Override
public boolean keyDown(int keycode) {
    if(keycode == Input.Keys.BACK) {
        pause();
    }
    return false;
}

but calling the pause() method isn't enough, what can i call to make it act like the home button ?


Solution

  • Gdx.input.setCatchBackKey(true); // This will prevent the app from being paused.
    

    Use Interfacing and call platform specific code by core module

    Inside core module

    interface PlatformService{
    
        fun moveToStack()
    }
    

    Implement above interface in Android module

    @Override
    public void moveToStack() {
        this.moveTaskToBack(true);
    }
    

    Get reference of your implementation in core module and call implemented method on keyDown back button

     Gdx.input.setInputProcessor(new InputAdapter(){
            @Override
            public boolean keyDown(int keycode) {
    
                if (keycode==Input.Keys.BACK){
                     platformService.moveToStack();
                }
    
                return super.keyDown(keycode);
            }
        });