How do I manually pause an activity in Android?

android

Solution

To override the behavior of Back Button you can override `onBackPressed()` method in your `Activity` which is called when you press the back button:

@Override
public void onBackPressed() {
   moveTaskToBack(true);  // "Hide" your current Activity
}

By using `moveTaskToBack(true)` your Activity is sent to background but there is no guarantee it will remain in the "pause" state, Android can kill it if it needs memory. I don't know why you want this behavior I think it would be better to save Activity state and recover it when you are back or simply, launch another Intent with the new Activityyou want to bring.

Problem

When you press the back button in Android it calls finish() under the hood, and I want it to be replaced with a pause behavior, and I have found no documentation that let's you trigger that manually. EDIT: Ok, this needs more code I guess ``` public boolean onKeyDown(int keyCode, KeyEvent event) { int Action = event.getAction(); if (Action == KeyEvent.ACTION_DOWN) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { //Default Implementation calls finish(); //I want to call Pause, which should call onPause and then send my app in the background ! } } } ``` I just tried onBackPressed, it doesn't even get hit with the above code on Android 4.3 at least. I tried manually calling onPause() but that just renders my app into an invalid state.

Original source