Disable back button in android
Asked Answered
S

20

374

How to disable back button in android while logging out the application?

Secundines answered 24/1, 2011 at 8:26 Comment(4)
Can you be little more clear on the question? If you are looking for overwriting the back button default behavior then refer this question here. #2000602Searchlight
Please don't do this unless you have a good reason, as breaking the expected model of operation very slightly hurts the entire platformEmpanel
You would want to do it if you have to deal with a stupid Samsung S4 where the back button is touch sensitive (not physical), right on the edge of the phone, which is already so touch sensitive that a palm resting against the side will go back.Farming
It is against Android Quality and Design guide, role UX-N1.Cultigen
S
714

Override the onBackPressed method and do nothing if you meant to handle the back button on the device.

@Override
public void onBackPressed() {
   if (shouldAllowBack()) {
       super.onBackPressed();
   } else {
       doSomething();
   }
}
Searchlight answered 24/1, 2011 at 8:37 Comment(4)
This is much better and cleaner than overriding the key handling methods, and has the same effect. Great answer!Adulthood
Great solution dude. Is there any way to do like this with home button?Akim
This is great! I actually wanted to always return to my main activity when pressing back from any other activity, and overriding this method lets me do that very easily.Katlaps
Oops I forget to remove super.onBackPressed().Androsterone
B
190

If looking for a higher api level 2.0 and above this will work great

@Override
public void onBackPressed() {
    // Do Here what ever you want do on back press;
}

If looking for android api level upto 1.6.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_BACK) {
     //preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
     return true;
     }
     return super.onKeyDown(keyCode, event);    
}

Write above code in your Activity to prevent back button pressed

Byrom answered 24/1, 2011 at 8:36 Comment(3)
This method is more backwards compatible than using onbackpressed due to onbackpressed's api level requirementReilly
Great answer. Although I don't need it for my project, I appreciate that you provided both the old and new methods. This should be marked as correct answer. +1Katlaps
@Javanator the second one wouldn't work for me (for API level 16 for example), but the first one works like a charmDougall
C
48

You can do this simple way Don't call super.onBackPressed()

Note:- Don't do this unless and until you have strong reason to do it.

@Override
public void onBackPressed() {
// super.onBackPressed();
// Not calling **super**, disables back button in current screen.
}
Commonplace answered 23/7, 2015 at 19:19 Comment(3)
An explanation as to "why not" would be great. Thanks.Hebdomadal
Not calling .super is important!Photomechanical
@almostabeginner because not calling super will invalidate the normal use of back button. users will freak out when a normally-working button stops working. they may think the app is buggy or the phone is malfunctioning etc. your app will be the culprit in the end.Chronometer
L
27

Simply override the onBackPressed() method.

@Override
public void onBackPressed() { }
Lepidus answered 25/6, 2015 at 5:42 Comment(0)
R
14

I am using it.............

 @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode==KeyEvent.KEYCODE_BACK)
        Toast.makeText(getApplicationContext(), "back press",      
     Toast.LENGTH_LONG).show();

    return false;
       // Disable back button..............
}
Rutan answered 27/3, 2014 at 15:13 Comment(0)
B
10

Just override the onBackPressed() method and no need to call the super class of onBackPressed method or others..

@Override
public void onBackPressed()
{
   
}

Or pass your current activity into the onBackPressed() method.

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

Replace your require activity name to myActivity.

if you are using fragment then first of all call the callParentMethod() method

public void callParentMethod(){
    context.onBackPressed(); // instead of context use getActivity or something related
}

Then call the empty method

@Override
public void onBackPressed()
{

}

Updated implementation for activity:

onBackPressedDispatcher.addCallback(this) {
    // Handle the back button event
}

Updated implementation for fragment:

requireActivity().onBackPressedDispatcher.addCallback(this) {
       // Handle the back button event
}
Blanka answered 3/6, 2018 at 20:14 Comment(0)
J
9

If you want to make sure your android client application is logged out from some server before your Activity gets killed --> log out with a service on its own thread (that's what you're supposed to do anyway).

Disabling the back button won't solve anything for you. You'll still have the same problem when the user receives a phone call for instance. When a phone call is received, your activity has about as much chances of getting killed before it gets a reliable answer back from the network.

That's why you should let a service wait on its own thread for the answer from the network, and then make it try again if it doesn't succeed. The android service is not only much less likely to get killed before it gets an answer back, but should it really get killed before finishing the job, it can always get revived by AlarmManager to try again.

Jussive answered 24/1, 2011 at 9:56 Comment(0)
T
9

Disable back buttton in android

@Override
public void onBackPressed() {
    return;
}
Triolein answered 29/7, 2019 at 6:30 Comment(0)
A
8

You can override the onBackPressed() method in your activity and remove the call to super class.

@Override
public void onBackPressed() {
  //remove call to the super class
  //super.onBackPressed();
}
Alluvium answered 24/3, 2018 at 12:40 Comment(0)
R
6

if you are using FragmentActivity. then do like this

first call This inside your Fragment.

public void callParentMethod(){
    getActivity().onBackPressed();
}

and then Call onBackPressed method in side your parent FragmentActivity class.

@Override
public void onBackPressed() {
  //super.onBackPressed();
  //create a dialog to ask yes no question whether or not the user wants to exit
  ...
}
Revolutionary answered 16/12, 2014 at 6:46 Comment(0)
C
6

Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();

@Override
public void onBackPressed() {

}
Criswell answered 5/12, 2017 at 11:58 Comment(0)
G
5

If you want to disable your app while logging out, you can pop up a non-cancellable dialog.

Galleon answered 24/1, 2011 at 21:29 Comment(0)
S
4

Apart form these two methods from answer above.

onBackPressed() (API Level 5, Android 2.0)

onKeyDown() (API Level 1, Android 1.0)

You can also override the dispatchKeyEvent()(API Level 1, Android 1.0) like this,

dispatchKeyEvent() (API Level 1, Android 1.0)

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    // TODO Auto-generated method stub
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        return true;
    }
    return super.dispatchKeyEvent(event);
}
Sherburn answered 23/6, 2017 at 6:20 Comment(0)
S
4

As Android have added gesture feature of swipe for back from Android 13

Android 13 and above

From Android 13 and above onBackPress is deprecated. So for above Android 13 you need to use onBackPressedDispatcher. First you need to add callBack in onCreate of Activity preferred add just after setContentView or binding view

JAVA

getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { // true: for prevent back and do something in handleOnBackPressed
        @Override
        public void handleOnBackPressed() {
            // Do Something
        }
    });

Kotlin

onBackPressedDispatcher.addCallback(object: OnBackPressedCallback(true) {// true: for prevent back and do something in handleOnBackPressed
            override fun handleOnBackPressed() {
                // Do Something
            }
        })

Below Android 13

Java

@Override
public void onBackPressed() {
   if (shouldAllowBack()) { // true for allow back
       super.onBackPressed();
   } else {
       //do Something
   }
}

Kotlin

override fun onBackPressed() {
    if (shouldAllowBack()) { // true for allow back
        super.onBackPressed()
    } else {
        //do Something
    }
}
Sheldon answered 26/7, 2023 at 6:31 Comment(2)
inside the handleOnBackPressed() how do I call the default behaviour to happen after I'm done with my logic?Nestorius
You can use onBackPressedDispatcher.onBackPressed() whenever you want back pressed.Sheldon
Y
3

You just need to override the method for back button. You can leave the method empty if you want so that nothing will happen when you press back button. Please have a look at the code below:

@Override
public void onBackPressed() 
{
   // Your Code Here. Leave empty if you want nothing to happen on back press.
}
Yongyoni answered 26/7, 2016 at 13:4 Comment(0)
I
3

remove super.onBackPressed() from public void onBackPressed() work great. its tested in android 9

Irs answered 12/6, 2019 at 11:27 Comment(0)
S
2

For me just overriding onBackPressed() did not work but explicit pointing which activity it should start worked well:

@Override
public void onBackPressed(){
  Intent intent = new Intent(this, ActivityYouWanToGoBack.class);
  startActivity(intent);
}
Son answered 19/4, 2017 at 13:14 Comment(0)
H
1

Try this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
 if (keyCode == KeyEvent.KEYCODE_BACK) {

   return true;
 }
   return super.onKeyDown(keyCode, event);    
}
Hydria answered 16/2, 2019 at 5:19 Comment(0)
A
1

Android 13 Kotlin

onBackPressedDispatcher.addCallback(object: OnBackPressedCallback(true) {
            /* override back pressing */
            override fun handleOnBackPressed() {
                //Your code here
            }
        })
Agone answered 28/9, 2022 at 4:21 Comment(0)
N
0

With jetpack compose we can use:

setContent {
   BackHandler {}
...
}
Nutlet answered 15/3 at 1:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.