Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I manually pause an activity in Android?

Tags:

android

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.

like image 798
RelativeGames Avatar asked Dec 05 '25 10:12

RelativeGames


1 Answers

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.

like image 105
Andres Avatar answered Dec 07 '25 00:12

Andres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!