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)

Steve2955
  • 639
  • 1
  • 5
  • 17
  • 3
    use onKeyDown method in order to overrride back action – siddhesh Sep 16 '16 at 13:23
  • ...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. – Opiatefuchs Sep 16 '16 at 13:30
  • 2
    @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.... – Opiatefuchs Sep 16 '16 at 13:30
  • 2
    Your onBackPressed() method is doing fine. Problem's not there – Anton Kazakov Sep 16 '16 at 13:31
  • @Opiatefuchs I haven't overriden onKeyDown – Steve2955 Sep 16 '16 at 13:32
  • Try to add call to a super onBackPressed in the overriden one and check if app will close. – Shadov Sep 16 '16 at 13:33
  • 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();` – Opiatefuchs Sep 16 '16 at 13:45
  • 1
    @Opiatefuchs The Log and the Toast, both didn't work, but I now switched to the onKeyDown method and it is working. – Steve2955 Sep 16 '16 at 13:48

7 Answers7

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.

Opiatefuchs
  • 9,800
  • 2
  • 36
  • 49
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);
    }
}
BitByteDog
  • 3,074
  • 2
  • 26
  • 39
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

Saveen
  • 4,120
  • 14
  • 38
  • 41
  • 1
    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() – Opiatefuchs Sep 16 '16 at 13:43
  • super.onBackPressed(); didn't do anything, but for some reason onKeyDown worked for me. – Steve2955 Sep 16 '16 at 13:47
  • for sure, `onKeyDown` will work, just try my solution in the comment with passing the correct context....the onBackPressed should work... – Opiatefuchs Sep 16 '16 at 13:47
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);
}
}
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
0

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

0

working fine onKeyDown function return type false;

@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {
  

    return false;

}
amra ram
  • 81
  • 1
  • 2
-1

Just Remove super.onBackPressed() it will work

vijay
  • 1,475
  • 2
  • 16
  • 26