Android : Execute some code after back button is pressed

If you have a requirement wherein you want to execute a method or a block of custom java code after the back button is pressed just before the back button action takes place, you need to Override the back button using onBackPressed() method.


import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState) {


    public void onBackPressed() {
        Toast.makeText(MainActivity.this, "Back Button is being Pressed!", Toast.LENGTH_SHORT).show();


Note: When the Back Button is being pressed you would see that the Toast Message is displayed and the Application quits.

If you wish that No Back Action is to be performed when the Back Button has clicked check this post: Disable Android Back Button Programmatically

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap