Synchronous AlertDialogs in Android

In general Android does not want developers creating alert dialogs that block the flow of code, but for those situations where it is needed, there is a way to force a dialog to wait. The approach essentially uses a handler to create a slightly more elegant version of a busy loop.

private boolean resultValue;
public boolean getDialogValueBack(Context context)
{
final Handler handler = new Handler()
{
@Override
public void handleMessage(Message mesg)
{
throw new RuntimeException();
}
};

AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Title");
alert.setMessage("Message");
alert.setPositiveButton("Return True", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
resultValue = true;
handler.sendMessage(handler.obtainMessage());
}
});
alert.setNegativeButton("Return False", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
resultValue = false;
handler.sendMessage(handler.obtainMessage());
}
});
alert.show();

try{ Looper.loop(); }
catch(RuntimeException e){}

return resultValue;
}