The dialog appears twice when you click the back button.

In the code, the dialog is displayed twice when I click the back button. Can someone tell me how to get a dialogue only once?

public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK))
        {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
         }

public void onBackPressed()
    {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Do you want to save configuration?");
            builder.setPositiveButton
                           ("Yes", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int id)
                {
                //here saveConfiguration is boolean type    
                    if (saveConfiguration()) 

                                              {
                        dialog.dismiss();
                        finish();

                    }
                    else
                    {
                        dialog.dismiss();
                    }

                }
            });
            builder.setNegativeButton("No", new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int id)
                {
                    dialog.dismiss();
                    finish();
                }
            });
            builder.show();
    }



}
+5
source share
2 answers

Your dialog goes twice because it consumes two events from the back key, that is, the down key and the up key .. restricts this to one of them.

             if (event.getAction() != KeyEvent.ACTION_DOWN)
 {

      /* Now call onBackPressed method here */
 }
+14
source

onBackPressed () is the standard action method

, , onKeyDown , super.onKeyDown(keyCode, event) ( , , onBackPressed() );

, onKeyDown, onBackPressed(), onBackPressed() .

+1

All Articles