1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.accessibilityservice.cts; 18 19 import static com.google.common.truth.Truth.assertThat; 20 21 import android.accessibility.cts.common.InstrumentedAccessibilityService; 22 import android.app.UiAutomation; 23 import android.view.accessibility.AccessibilityEvent; 24 25 import androidx.annotation.NonNull; 26 27 import com.android.compatibility.common.util.TestUtils; 28 29 import java.util.concurrent.atomic.AtomicBoolean; 30 31 /** 32 * A stub accessibility service for waiting on {@link AccessibilityEvent}s using an 33 * {@link UiAutomation.AccessibilityEventFilter}. 34 */ 35 public class StubEventCapturingAccessibilityService extends InstrumentedAccessibilityService { 36 private final AtomicBoolean mReceivedEvent = new AtomicBoolean(); 37 private final Object mWaitObject = new Object(); 38 private UiAutomation.AccessibilityEventFilter mEventFilter; 39 40 @Override onAccessibilityEvent(@onNull AccessibilityEvent event)41 public void onAccessibilityEvent(@NonNull AccessibilityEvent event) { 42 if (mEventFilter != null) { 43 if (mEventFilter.accept(event)) { 44 synchronized (mWaitObject) { 45 mReceivedEvent.set(true); 46 mWaitObject.notifyAll(); 47 } 48 } 49 } 50 } 51 52 /** 53 * Waits on an {@link AccessibilityEvent} to be accepted by the event filter. 54 * 55 * Resets the filter & waiting state after a successful wait. 56 * 57 * @throws AssertionError on timeout. 58 * @see #setEventFilter 59 */ waitOnEvent(long timeoutMs, String condition)60 public void waitOnEvent(long timeoutMs, String condition) { 61 assertThat(mEventFilter).isNotNull(); 62 TestUtils.waitOn(mWaitObject, mReceivedEvent::get, timeoutMs, condition); 63 mEventFilter = null; 64 mReceivedEvent.set(false); 65 } 66 setEventFilter(@onNull UiAutomation.AccessibilityEventFilter filter)67 public void setEventFilter(@NonNull UiAutomation.AccessibilityEventFilter filter) { 68 mEventFilter = filter; 69 } 70 } 71