Close dialogs and activity on Escape down

Currently closing dialogs and activities that look like dialogs
requires the user to release the Escape key, that is, the up
event; applying the action on the down event will increase
responsiveness.

Bug: 324221986
Test: Tested on Google Play voice search, and private DNS dialog
in the Settings app.

Change-Id: Ie1fd3a47955e0c693f9b5eaa6ba788a57e8973ed
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index ab9a4ec..23fe731 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -3927,6 +3927,7 @@
 
         if (keyCode == KeyEvent.KEYCODE_ESCAPE && mWindow.shouldCloseOnTouchOutside()) {
             event.startTracking();
+            finish();
             return true;
         }
 
@@ -4027,10 +4028,7 @@
         }
 
         if (keyCode == KeyEvent.KEYCODE_ESCAPE
-                && mWindow.shouldCloseOnTouchOutside()
-                && event.isTracking()
-                && !event.isCanceled()) {
-            finish();
+                && event.isTracking()) {
             return true;
         }
 
diff --git a/core/java/android/app/Dialog.java b/core/java/android/app/Dialog.java
index d0d76a4..0e20138 100644
--- a/core/java/android/app/Dialog.java
+++ b/core/java/android/app/Dialog.java
@@ -672,7 +672,16 @@
      */
     @Override
     public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
-        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE) {
+        if (keyCode == KeyEvent.KEYCODE_BACK) {
+            event.startTracking();
+            return true;
+        }
+        if (keyCode == KeyEvent.KEYCODE_ESCAPE) {
+            if (mCancelable) {
+                cancel();
+            } else {
+                dismiss();
+            }
             event.startTracking();
             return true;
         }
@@ -712,11 +721,6 @@
                     }
                     break;
                 case KeyEvent.KEYCODE_ESCAPE:
-                    if (mCancelable) {
-                        cancel();
-                    } else {
-                        dismiss();
-                    }
                     return true;
             }
         }