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.

package com.code2care.tools.sample;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;


public class MainActivity extends ActionBarActivity {

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


    }


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

        super.onBackPressed();
    }
}

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




Recent Posts:




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, Video Tutorials, Code Snippets, How Tos, Blogs, Articles, etc.