Q:

Handle Back button in AlertDialog.Builder

I would like to finish() the app whenever I press the back button, when the dilog builder is shown.
I have the following code
private void displaydialog() 
{
    final LayoutInflater inflator = LayoutInflater.from(this);
    final View settingsview = inflator.inflate(R.layout.nointernet, null);
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setIcon(R.drawable.reminderalert);
    builder.setTitle("No Network...");
    builder.setView(settingsview);

    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() 
    {
        @Override
        public void onClick(DialogInterface dialog, int which) 
        {
            startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
            dialog.dismiss();
        }
    });

    builder.create().show();
}

I am not sure where to insert the OnKeylistener and Key Event. Can somebody guide me on when/how to insert the listener?
Thanks!

A:

If you want to finish the current Activity when Negative Button of AlertDialog is clicked or hardware back button is clicked(when AlertDialog is shown) then do something like below,
pDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                // if from activity
                finish();

            }

        });

