Fix NPE in UiAutomationManager

Fix a race condition that UiAutomationService is
destroyed just before main thread processes the
connection.

Bug: 328277279
Test: UiAutomationManagerTest
Merged-In: I0352ad255930ed58c111d5733e7ca2ae75fdf8fa
Change-Id: I0352ad255930ed58c111d5733e7ca2ae75fdf8fa
diff --git a/services/accessibility/java/com/android/server/accessibility/UiAutomationManager.java b/services/accessibility/java/com/android/server/accessibility/UiAutomationManager.java
index f69104d..3b9340b 100644
--- a/services/accessibility/java/com/android/server/accessibility/UiAutomationManager.java
+++ b/services/accessibility/java/com/android/server/accessibility/UiAutomationManager.java
@@ -274,8 +274,10 @@
             mMainHandler.post(() -> {
                 try {
                     final IAccessibilityServiceClient serviceInterface;
+                    final UiAutomationService uiAutomationService;
                     synchronized (mLock) {
                         serviceInterface = mServiceInterface;
+                        uiAutomationService = mUiAutomationService;
                         if (serviceInterface == null) {
                             mService = null;
                         } else {
@@ -286,8 +288,8 @@
                     // If the serviceInterface is null, the UiAutomation has been shut down on
                     // another thread.
                     if (serviceInterface != null) {
-                        if (Flags.addWindowTokenWithoutLock()) {
-                            mUiAutomationService.addWindowTokensForAllDisplays();
+                        if (Flags.addWindowTokenWithoutLock() && uiAutomationService != null) {
+                            uiAutomationService.addWindowTokensForAllDisplays();
                         }
                         if (mTrace.isA11yTracingEnabledForTypes(
                                 AccessibilityTrace.FLAGS_ACCESSIBILITY_SERVICE_CLIENT)) {