Skip to content

Commit

Permalink
Merge pull request #252 from metalhead8816/handler_update
Browse files Browse the repository at this point in the history
Add implementation of sendMessageAtFrontOfQueue on ShadowHandler
  • Loading branch information
jberkel committed May 8, 2012
2 parents c7d0264 + bcc9e9a commit 000fd83
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
Expand Up @@ -108,6 +108,20 @@ public void run() {
return true;
}

private final boolean sendMessageToFrontDelayed(final Message msg, long delayMillis) {
messages.add(0, msg);
postAtFrontOfQueue(new Runnable() {
@Override
public void run() {
if (messages.contains(msg)) {
routeMessage(msg);
messages.remove(msg);
}
}
});
return true;
}

private void routeMessage(Message msg) {
if(callback != null) {
callback.handleMessage(msg);
Expand All @@ -128,6 +142,11 @@ public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
return sendMessageDelayed(msg, delayMillis);
}

@Implementation
public final boolean sendMessageAtFrontOfQueue(Message msg) {
return sendMessageToFrontDelayed(msg, 0L);
}

@Implementation
public final Looper getLooper() {
return looper;
Expand Down
23 changes: 23 additions & 0 deletions src/test/java/com/xtremelabs/robolectric/shadows/HandlerTest.java
Expand Up @@ -194,6 +194,29 @@ public void testPostAtFrontOfQueueThenRunMainLooperOneTaskAtATime_shouldRunFront
assertThat(task1.wasRun, equalTo(true));
}

@Test
public void testSendMessageAtFrontOfQueueThenRunMainLooperOneMsgAtATime_shouldRunFrontOfQueueMsgFirst() throws Exception {
Handler handler = new Handler();

ShadowLooper.pauseMainLooper();
// Post two messages to handler. Handle first message and confirm that msg posted
// to front is removed.
handler.obtainMessage(123).sendToTarget();
Message frontMsg = handler.obtainMessage(345);
boolean result = handler.sendMessageAtFrontOfQueue(frontMsg);

assertTrue(result);

assertTrue(handler.hasMessages(123));
assertTrue(handler.hasMessages(345));
ShadowHandler.runMainLooperOneTask();
assertTrue(handler.hasMessages(123));
assertFalse(handler.hasMessages(345));
ShadowHandler.runMainLooperOneTask();
assertFalse(handler.hasMessages(123));
assertFalse(handler.hasMessages(345));
}

@Test
public void sendEmptyMessage_addMessageToQueue() {
Robolectric.pauseMainLooper();
Expand Down

0 comments on commit 000fd83

Please sign in to comment.