Fix triggering messages sent from non-Looper threads.

This can happen for instrumented tests that are run on a non-Looper
thread. If these tests send a message to a Looper thread to start the
test procedure, they should just triger the message directly as before.

PiperOrigin-RevId: 354066836
This commit is contained in:
tonihei 2021-01-27 12:39:39 +00:00 committed by Oliver Woodman
parent 27d729f8c5
commit a60938db96

View File

@ -149,10 +149,16 @@ public class FakeClock implements Clock {
protected synchronized void addPendingHandlerMessage(HandlerMessage message) {
handlerMessages.add(message);
if (!waitingForMessage) {
// If this isn't executed from inside a message created by this class, make sure the current
// looper message is finished before handling the new message.
waitingForMessage = true;
new Handler(checkNotNull(Looper.myLooper())).post(this::onMessageHandled);
// This method isn't executed from inside a looper message created by this class.
@Nullable Looper currentLooper = Looper.myLooper();
if (currentLooper == null) {
// This message is triggered from a non-looper thread, so just execute it directly.
maybeTriggerMessage();
} else {
// Make sure the current looper message is finished before handling the new message.
waitingForMessage = true;
new Handler(checkNotNull(Looper.myLooper())).post(this::onMessageHandled);
}
}
}