How To Disable Back Press In Android

I think you know the architecture of application where activities are being added like stack i.e, LIFO (Last In First Out). Backpress will pop last activity from the memory stack and you are able to view previous activity. In Android we can make changes to this default behavior of an android activity by either overriding onBackPressed() or onKeyDown() method in Activity class.

Following are the 2 methods that i mentioned above,

Method 1: Override onBackPressed()

When you press back button on the device this function gets called and the taking you to the previous activity performed by calling the super class function i.e, super.onBackPressed(). Without this function being called nothing happens so if you want to disable backpress then override the onBackPressed() and comment the calling to super class.

Open your Activity class

public void onBackPressed() {
  // super.onBackPressed(); commented this line in order to disable back press
  //Write your code here
  Toast.makeText(getApplicationContext(), "Back press disabled!", Toast.LENGTH_SHORT).show();

Method 2: Override onKeyDown()

This is an another solution. This is also part of the process being done when someone presses the back button. But here we catch the user input i.e, keypress before reaching to onBackPressed(). The idea behind this method is to detects whether it is a back button key press then break the flow of execution.

Open your Activity class

public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {
        super.onKeyDown(keyCode, event);
        return true;
    return false;
About author

Rojer is a programmer by profession, but he likes to research new things and is also interested in writing. Devdeeds is his blog, where he writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

Your email address will not be published. Required fields are marked *