151

How to handle a back button in an activity? I have some buttons. If I click one of the buttons, it's redirecting to the buttons which I required. It's working fine but when I press back button it gets finished.

How to solve this problem? I have only one activity for all those buttons.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if ((keyCode == KeyEvent.KEYCODE_BACK)) 
    {
        return false; //I have tried here true also
    }
    return super.onKeyDown(keyCode, event);
}

I have used above code to handle back button but it's not working. When I press back button its struck there itself.

cottontail
  • 10,268
  • 18
  • 50
  • 51
Shekhar
  • 1,767
  • 3
  • 16
  • 19

9 Answers9

361

You can handle it like this:

for API level 5 and greater

@Override
public void onBackPressed() {
    // your code.
}

older than API 5

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // your code
        return true;
    }

    return super.onKeyDown(keyCode, event);
}
PaulR
  • 3,223
  • 1
  • 21
  • 32
Saurabh Pareek
  • 7,126
  • 4
  • 28
  • 29
19

In addition to the above I personally recommend

onKeyUp():

Programatically Speaking keydown will fire when the user depresses a key initially but It will repeat while the user keeps the key depressed.*

This remains true for all development platforms.

Google development suggested that if you are intercepting the BACK button in a view you should track the KeyEvent with starttracking on keydown then invoke with keyup.

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        event.startTracking();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
            && !event.isCanceled()) {
        // *** Your Code ***
        return true;
    }
    return super.onKeyUp(keyCode, event);
}
Richard Sites
  • 186
  • 2
  • 9
18

For both hardware device back button and soft home (back) button e.g. " <- " this is what works for me.

(*Note I have an app bar / toolbar in the activity)

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            //finish();
            onBackPressed();
            break;
    }
    return true;
}



@Override
public void onBackPressed() {
   //Execute your code here
   finish();

}
cottontail
  • 10,268
  • 18
  • 50
  • 51
S bruce
  • 1,514
  • 3
  • 16
  • 24
  • I used finish and it doesn't go back to the previous activity. – Si8 Nov 04 '16 at 11:00
  • 2
    "finish()" closes your current activity only. You need to handle going back to your previous activity by using intent. Btw, your previous activity should still be open if you did not "finish()" it when navigating from it previously. – S bruce Nov 04 '16 at 11:57
  • I am testing out something and will update you. Thanks for the response. – Si8 Nov 04 '16 at 15:06
  • 1
    Just use super.onBackPressed() instead of finish() – b00n12 Dec 10 '16 at 13:25
9

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

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

Android 2.0 introduced a new onBackPressed method, and these recommendations on how to handle the Back button

Umesh K
  • 13,436
  • 25
  • 87
  • 129
9

You should use:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
            && keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        // Take care of calling this method on earlier versions of
        // the platform where it doesn't exist.
        onBackPressed();
    }

    return super.onKeyDown(keyCode, event);
}

@Override
public void onBackPressed() {
    // This will be called either automatically for you on 2.0
    // or later, or by the code above on earlier versions of the
    // platform.
    return;
}

As defined here: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

If you are using an older version to compile the code, replace android.os.Build.VERSION_CODES.ECLAIR by 5 (you can add a private int named ECLAIR for example)

neteinstein
  • 17,529
  • 11
  • 93
  • 123
3

This is a simple way of doing something.

    @Override
        public void onBackPressed() {
            // do what you want to do when the "back" button is pressed.
            startActivity(new Intent(Activity.this, MainActivity.class));
            finish();
        }

I think there might be more elaborate ways of going about it, but I like simplicity. For example, I used the template above to make the user sign out of the application AND THEN go back to another activity of my choosing.

1

This helped me ..

@Override
public void onBackPressed() {
    startActivity(new Intent(currentActivity.this, LastActivity.class));
    finish();
}

or you can even use this for drawer toggle also

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
        startActivity(new Intent(currentActivity.this, LastActivity.class));
    finish();

}
cottontail
  • 10,268
  • 18
  • 50
  • 51
Shubham
  • 1,205
  • 1
  • 12
  • 15
0
intent = Intent(this@activity2,activity1::class.java)
startActivity(intent)
Manikandan
  • 21
  • 2
0

If you just want to stop the back button from working without raising warnings, put this in onCreate (you might need some extra imports):

this.onBackPressedDispatcher.addCallback(this, false) { }
KTibow
  • 495
  • 6
  • 18