Shah
Shah

Reputation: 5020

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;

    }

Upvotes: 2

Views: 2381

Answers (3)

Suresh
Suresh

Reputation: 9605

AFAIK KeyCode.KEYCODE_HOME is never propagated to Activty/Dialog when HOME key is pressed, HOME key is intercepted in framework to guarantee homescreen/activity registered for "android.intent.category.HOME" always brought to focus.

If intercepting HOME key is allowed in applications, there is a possibility that an evil app can prevent the user from exiting the application and using the phone functionality.

Upvotes: 1

Niranj Patel
Niranj Patel

Reputation: 33258

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..

Upvotes: 3

Krishna
Krishna

Reputation: 1474

Try this mate....

 @Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if ((keyCode == KeyEvent.KEYCODE_HOME)) {    
         Log.d(this.getClass().getName(), "home button pressed");   
      }  
       return super.onKeyDown(keyCode, event);
     } 

Upvotes: 0

Related Questions