首先,我们封装一个Toast
public static boolean waitForToast(String toast, long timeout) {
return waitForToast(toast, Function::identity, timeout);
}
public static boolean waitForToast(String toast, Runnable r, long timeout) {
UiAutomation automation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
try {
AccessibilityEvent event = automation.executeAndWaitForEvent(
r,
e -> isToastShow(e, toast),
timeout);
event.recycle();
return true;
} catch (TimeoutException e) {
return false;
}
}
private static boolean isToastShow(AccessibilityEvent event, String toast) {
if (event.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
Parcelable parcelable = event.getParcelableData();
if (!(parcelable instanceof Notification)) { // without Notification is Toast
String toastMessage = "" + event.getText().get(0);