Search code examples
androidonkeydownandroid-homebutton

need help in Home Button in android


hi all i want to intercept my Home Button.
what i want is that whenever i press a Home Button i want to display a Alert dialog for Are you sure you want to Quit. if Yes then Finish the activity else do nothing. I have got to know that
when ever we Press Home Button the following callbacks are performed in order.

onSaveInstanceState(Bundle outState)

onPause()

onStop()

So i have overRide onSaveInstanceState Method and set my Alert dialog Code there but it gives me Exception on Dialog. Please Help friends. Guide me a lil..about it.

UPDATED:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
boolean flag = displayAlertDialog();
        if(flag){
             this.finish();
         super.onSaveInstanceState(savedInstanceState);
        }
}  

displayAlertDialog Method:

private boolean isExit = false;
public boolean displayAlertDialog()
    {
        //final boolean flag=true;
        int a = 0;
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setMessage("Are you sure you want to Exit?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                isExit = true;
            }

        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                isExit = false;
                dialog.cancel();
            }
        });
        alt_bld.show();
    return isExit;

    }

Solution

  • you cant open dialog on home button. but you can open any activity on home button by user choose action like home or your activity..