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

Try Out Code2care Dev Tools:


Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.