import android.app.Notification;
import android.app.UiAutomation;
import android.os.Parcelable;
import android.support.test.InstrumentationRegistry;
import android.view.accessibility.AccessibilityEvent;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
public class Toast {
public static boolean checkToast(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);
return toastMessage.contains(toast);
}
}
return false;
}
}
使用
boolean toast = checkToast("请连接有效设备",10000);
//10000为等待时间,检查10S内是否有“请连接有效设备”Toast弹出