Detecting android device hardware back button / soft back button press is very easy. But be careful while overriding the default back button action as it is not suggested to change the android default user experience.

Method 1

Override the onBackPressed() method and take the action inside this function.

@Override
	public void onBackPressed() {
		// Write your code here

		super.onBackPressed();
	}
Author

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.

  • kam

    while seeing codes i’m really irritated in ur website try to provide codes in full screen feeling shit on seing ur website even u provide best codes but user interface wil shul be good but it’s nt gud in ur site

    • Ninjaxin

      is this even english?

      • forresthopkinsa

        I don’t think it is, no

  • Aman

    how to detect back press in fragments

  • vinod

    when click on back button, stop activity. don’t choose slide menu activity. my code is here:

    @Override

    public void onBackPressed() {

    if(mDrawerLayout.isDrawerOpen(mDrawerList)){

    mDrawerLayout.closeDrawer(mDrawerList);

    }else {

    //mDrawerLayout.openDrawer(mDrawerList);

    Intent resultIntent = new Intent();

    // TODO Add extras or a data URI to this intent as appropriate.

    setResult(Activity.RESULT_OK, resultIntent);

    finish();

    }

    }

    plz help me….

  • sumit kumawat

    but how to implement in case of multiple fargment in naviagtion drawer

  • manish jangid

    how to detect back button press when activity is on background
    ??

    • Thomas

      open a transparent activity

  • deepak sharma

    how to go through the nested fragments without having the fragmentactivity

  • farman

    how to detect Android Back button press on fragment