Search code examples
androidstackback-button

I want to control the stack and what happens when the user presses the back button on the Android system, not my app


I want to know if I can control the action my application takes when a user presses the back button on the android device instead of using the application's navigation that I created. Is there a way of creating an intent when the back button is pressed and also, is there a way to limit how many Activities from my app are in the stack (could I tell the android device to only remember the last 3 Activities from my app)


Solution

  • You just need to override onBackPressed in your activity and then you can do what you want. https://developer.android.com/reference/android/app/Activity.html#onBackPressed()

    There are also lots of answers here on stack overflow regarding manipulating the back stack (the stack of activities that are navigated through as one presses the back button.) I could post links to some random ones that I found, but you are probably best to search yourself. Read the docs and search for the android back stack.