InputDispatcher: Fix crash when there is an ANR after window removal

This addresses a bug in the change:
I47744cbd677cc74e26a102c50a2c11c68bc8aa89

InputDispatcher has an invariant that it can only send events to a
connection if it has a window. We did not check if the channel receiving
an ANR had a window before attempting to synthesize cancellations for
it.

Bug: 324330557
Bug: 210460522
Test: atest inputflinger_tests
Change-Id: I5f3013fe93c0f4d1bb0f58e7b2a241cffe5c5bf2
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index 3e999c7..6719006 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -2089,13 +2089,23 @@
     // pile up.
     ALOGW("Canceling events for %s because it is unresponsive",
           connection->getInputChannelName().c_str());
-    if (connection->status == Connection::Status::NORMAL) {
-        CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
-                                   "application not responding");
-        synthesizeCancelationEventsForConnectionLocked(connection, options,
-                                                       getWindowHandleLocked(
-                                                               connection->getToken()));
+    if (connection->status != Connection::Status::NORMAL) {
+        return;
     }
+    CancelationOptions options(CancelationOptions::Mode::CANCEL_ALL_EVENTS,
+                               "application not responding");
+
+    sp<WindowInfoHandle> windowHandle;
+    if (!connection->monitor) {
+        windowHandle = getWindowHandleLocked(connection->getToken());
+        if (windowHandle == nullptr) {
+            // The window that is receiving this ANR was removed, so there is no need to generate
+            // cancellations, because the cancellations would have already been generated when
+            // the window was removed.
+            return;
+        }
+    }
+    synthesizeCancelationEventsForConnectionLocked(connection, options, windowHandle);
 }
 
 void InputDispatcher::resetNoFocusedWindowTimeoutLocked() {