Override Back Button to Act Like Home Button

Override back button to act like home button

Most of the time you need to create a Service to perform something in the background, and your visible Activity simply controls this Service. (I'm sure the Music player works in the same way, so the example in the docs seems a bit misleading.) If that's the case, then your Activity can finish as usual and the Service will still be running.

A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:

// 2.0 and above
@Override
public void onBackPressed() {
moveTaskToBack(true);
}

// Before 2.0
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}

I think the preferred option should be for an Activity to finish normally and be able to recreate itself e.g. reading the current state from a Service if needed. But moveTaskToBack can be used as a quick alternative on occasion.

NOTE: as pointed out by Dave below Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button.

libgdx make android back button act like home button

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);
}
});

how to emulate home button on back button pressed

Try my code in your activity.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d(TAG, "onKeyDown: ");
if(keyCode == KeyEvent.KEYCODE_BACK){
goHome();
return true;
}
return super.onKeyDown(keyCode, event);
}

private void goHome() {
Intent i = new Intent(Intent.ACTION_MAIN);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
}

Do start the home screen when key back down.

Android: Phone Back Button on Main Activity

@Override
public void onBackPressed() {
// Behaves like you would have pressed the home-button
moveTaskToBack(true);
}

Back button works like home

try this,

@Override
public void onBackPressed() {
Intent backtoHome = new Intent(Intent.ACTION_MAIN);
backtoHome.addCategory(Intent.CATEGORY_HOME);
backtoHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(backtoHome);
}

Adding this to your Activity, will make it look like your app is responding to a Home Button Click event



Related Topics



Leave a reply



Submit