Android onBackPressed() is not being called?
Asked Answered
S

8

22

in my MainActivity, which extends from AppCompatActivity, I want to override the onBackPressed method like so:

@Override
public void onBackPressed() {
    Log.d("MainActivity","onBackPressed");
    Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}

but onBackPressed does not get called. How ever if I do not override onBackPressed, the application closes, when I press the backbutton and if I do override it it doesn't.

The rest of my activity looks like this:

public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private Drawer drawer;
private FloatingActionButton fab_test;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    fab_test = (FloatingActionButton) findViewById(R.id.fab_test);
    fab_test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(),"FAB Test pressed",Toast.LENGTH_SHORT).show();
        }
    });

    buildDrawer();

    getSupportFragmentManager().beginTransaction().add(R.id.fragmentContainer,page).commit();
}

@Override
public void onBackPressed() {
    Log.d("MainActivity","onBackPressed");
    Toast.makeText(getApplicationContext(),"onBackPressed",Toast.LENGTH_SHORT).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);      
    return true;
}
}

EDIT: I'm talking about the hardware-backbutton(not the actionbar one)

Schwarz answered 16/9, 2016 at 13:22 Comment(8)
use onKeyDown method in order to overrride back actionHousman
...you can easily put that code inside onBackPressed(), no need for onKeyDown . From the docs: Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want. There must be any other problem for this behaviour.Panteutonism
@Steve: Do you have overriden onKeyDown for back button? Because if you have done this anywhere in your code, possibly you haven´t returned true and onBackPressed is not called....Panteutonism
Your onBackPressed() method is doing fine. Problem's not thereRecursion
@Panteutonism I haven't overriden onKeyDownSchwarz
Try to add call to a super onBackPressed in the overriden one and check if app will close.Abney
You don´t need to call super.OnBackPressed(), the method should work without this. What exactly isn´t working? The Log? The Toast? If it´s the toast, maybe it´s because of your getApplicationContext() call. Just use this or getActivity().getApplicationContext();Panteutonism
@Panteutonism The Log and the Toast, both didn't work, but I now switched to the onKeyDown method and it is working.Schwarz
P
29

This question is already answered, but I feel to clear something here in this topic. Most comments and answeres point out to use super.onBackPressed() and that this is the cause of the not working method onBackPressed(). But that is not correct and important to let other beginners know. The method onBackPressed() does not need to use super.onBackPressed() . onBackPressed()also works if somebody, for example, comment super.onBackPressed() out.

As the questionier has written, he won´t use super.onBackPressed() because it will close the activity. So, the cause of this why it isn´t working, could be seperated into three possible causes:

  1. The Log doesn´t work because of a wrong filter in the logcat console
  2. The Toast dosn´t work because of the wrong passed context
  3. The OS is implemented wrong by the supplier.

Usually, the toast works by passing the correct context. In the case of questioner, simply passing this .

@Override
public void onBackPressed() {
    Log.d("MainActivity","onBackPressed");
    Toast.makeText(this,"onBackPressed",Toast.LENGTH_SHORT).show();
}

For the Log, simply set the correct filter on logcat.

I don´t care if somebody give downvotes now, but it must be clear for other beginners, that super.onBackPressed() must not be used.

Anyway, the use of onKeyDown() also is a solution.

Panteutonism answered 17/9, 2016 at 17:21 Comment(0)
J
21

The onBackPressed() is a default action called from onKeyDown() in API < 5 and a default action called from onKeyUp() from API level 5 and up. If onKeyUp() does not call super.onKeyUp(), onBackPressed() will not be called.

Documentation onKeyDown()

Documentation onKeyUp().

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    /*
     * without call to super onBackPress() will not be called when
     * keyCode == KeyEvent.KEYCODE_BACK
     */
    return super.onKeyUp(keyCode, event);
}

Also another reason that onBackPressed() may not be called is because you are using the soft back button on the actionbar, it that case the following is needed:

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
Jacelynjacenta answered 30/9, 2017 at 3:49 Comment(2)
This is the right answer for back press in the action bar.Burseraceous
public BOOLEAN onKeyUp... Are you returning a "BOOLEAN" here?Uncontrollable
G
6

You are missing, super.onBackPressed();

@Override
public void onBackPressed() {
    super.onBackPressed();
}

or you can use

@Override  
public boolean onKeyDown(int keyCode, KeyEvent event)  
{  
     //replaces the default 'Back' button action  
     if(keyCode==KeyEvent.KEYCODE_BACK)   {  
// something here
            finish();
     }  
     return true;  
 }  

thanks

Galangal answered 16/9, 2016 at 13:40 Comment(3)
as he stated out, and that´s correct, super.onBackPressed() will close the activity. You can easily override this and comment it out, the method will work without super.OnBackPressed()Panteutonism
super.onBackPressed(); didn't do anything, but for some reason onKeyDown worked for me.Schwarz
for sure, onKeyDown will work, just try my solution in the comment with passing the correct context....the onBackPressed should work...Panteutonism
D
1

For whoever is wondering, as most functionality is deprected API 30>, the following will surely help you a lot.

public class MainActivity extends AppCompatActivity {
private OnBackPressedCallback onBackPressedCallback;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    onBackPressedCallback = new OnBackPressedCallback(true) {
        @Override
        public void handleOnBackPressed() {
            // Your business logic to handle the back pressed event
            Log.d(TAG, "onBackPressedCallback: handleOnBackPressed");
        }
    };

    getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
}
}
Doucet answered 23/2, 2023 at 15:9 Comment(0)
E
0

make sure you are not calling onkeydown in your super view as it handles the back button clicking first.

Erst answered 23/3, 2019 at 21:27 Comment(0)
C
0

working fine onKeyDown function return type false;

@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {
  

    return false;

}
Cutie answered 29/7, 2022 at 21:43 Comment(0)
W
0

if u want to use onBackpressed and added some logic to finish the activity do not use super.onBackPressed

override fun onBackPressed() {
    

    if (session!!.backControl == "onBack") {
        session!!.backControl = "offBack"
        callFragment(AdminAssetFragment())
    } else if (session!!.backControlAmenities == "onBackAmenity") {
        session!!.backControlAmenities = "offBackAmenity"
        callFragment(AdminAmenityFragment())

    } else {
        finish()
    }
}
Weingarten answered 8/11, 2023 at 13:24 Comment(0)
F
-1

Just Remove super.onBackPressed() it will work

Finella answered 10/3, 2018 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.