Descartar constructor de diálogo de alerta de onpause

Estoy usando el siguiente código para mostrar un cuadro de diálogo de alerta con dos botones. Pero si el cuadro de diálogo no se disissed cuando la actividad está en pausa lanza un error. Sé que puedes descartar un diálogo usando .dismiss pero esto es un AlertDialog Builder no un diálogo. ¿Alguna idea de cómo hacer esto?

AlertDialog.Builder alertDialog = new AlertDialog.Builder(MyActivity.this); // Setting Dialog Title alertDialog.setTitle("Title"); // Setting Dialog Message alertDialog.setMessage("Message"); // Setting Positive "Yes" Button alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { //yes dialog.cancel(); } }); // Setting Negative "NO" Button alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //no dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); 

Puede obtener el AlertDialog al mostrar el diálogo:

 private AlertDialog dialog; // instance variable dialog = alertDialog.show(); // show and return the dialog 

En la onPause puede descartar el AlertDialog:

 @Override protected void onPause() { super.onPause(); if (alertDialog != null) { alertDialog.dismiss(); } } 

BTW el AlertDialog.Builder es un constructor porque usted puede utilizar el patrón del constructor así:

 dialog = AlertDialog.Builder(MyActivity.this) .setTitle("Title"); .setMessage("Message") [...] .show(); 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.