0

I want to show a AlertDialog in my app (whether quit app or not) when user press Home. I read that Home can't be overrided. So, I tried to override onPause method. It works fine when I press Back Button. But, the problem is in Home Button. It shows the dialog when I press Home button, but it sends the app to background before I do any action on the dialog. Is there a way to do some work before it sends the app to background?

My work:

@Override
protected void onPause() {
    super.onPause();
    if (clr.equals("red")) {
        AlertDialog.Builder alertD = new AlertDialog.Builder(this);
        alertD.setMessage("Do you want to cancel your schedule?")
                .setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {

                                finish();
                            }

                        });
        alertD.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        moveTaskToBack(true);
                    }
                });
        AlertDialog alertDD = alertD.create();
        alertDD.show();
    }
}
berserk
  • 2,690
  • 3
  • 32
  • 63

2 Answers2

0

That is very bad practice for usasbiliy of your app. And what behavior will be on long press of home button? User know that Home button is home button. Don't do this if you don't want to dissappoint users.

AndrOvip
  • 385
  • 2
  • 12
  • I know you wanted to post as a comment, but you can't :D Actually it is not bad. The user want to detect whenever it goes to background and do some work before. – berserk Dec 06 '13 at 06:34
0
 @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
           Log.v(LOG_TAG, "onKeyDown: " + event.getKeyCode());
       if (keyCode == KeyEvent.KEYCODE_BACK){                    
               // Do your work 
               return true;
       }
       return super.onKeyDown(keyCode, event);
}

you can use above method to prevent back key.

Do you see any APP can prevent home key ? None

You can only notice home key been tapped by receive the ACTION_CLOSE_SYSTEM_DIALOGS

MengMeng
  • 1,016
  • 6
  • 11
  • +1 for backpress. Can you tell me how to receive ACTION_CLOSE_SYSTEM_DIALOGS? – berserk Dec 06 '13 at 07:26
  • But you can only notice home buttom tapped , you can not prevent it.FYI:http://stackoverflow.com/questions/8878038/is-there-any-way-to-exit-the-application-when-home-button-is-pressed-on-android – MengMeng Dec 06 '13 at 07:28