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


Top Hashtags:

Advertisements

Advertisements




Advertisements