Minimum code for Android Alert Dialog Box in Unity

This was difficult to find, so here it is; the smallest snippet of code to present an AlertDialog (with OK button callback) to the user:

private class OnClickListener : AndroidJavaProxy {
    public readonly Action Callback;
    public OnClickListener(Action callback) : base("android.content.DialogInterface$OnClickListener") {
        Callback = callback;
    }
    public void onClick(AndroidJavaObject dialog, int id) {
        Callback();
    }
}

public override void ShowAlert(string title, string content) {
    AndroidJavaObject activity = null;
    using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
        activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    }
    activity.Call("runOnUiThread", new AndroidJavaRunnable(() => {
        AndroidJavaObject dialog = null;
        using (AndroidJavaObject builder = new AndroidJavaObject("android.app.AlertDialog$Builder", activity)) {
            builder.Call<AndroidJavaObject>("setTitle", title).Dispose();
            builder.Call<AndroidJavaObject>("setMessage", content).Dispose();
            builder.Call<AndroidJavaObject>("setPositiveButton", "OK", new OnClickListener(() => {
                Debug.Log("Button pressed");
            })).Dispose();
            dialog = builder.Call<AndroidJavaObject>("create");
        }
        dialog.Call("show");
        dialog.Dispose();
        activity.Dispose();
    }));
}

Note: I’m assuming all AndroidJavaObject objects need to be disposed (even when the same instance is returned in the case of the Builder), but that may not be the case.

You can remove the OnClickListener class and pass null as the final parameter for setPositiveButton if you do not need a callback.