MainThreadAsyncHandler { public static Handler getInstance() { if (sHandler != null) { return sHandler; } synchronized (MainThreadAsyncHandler.class) { if (sHandler == null) { sHandler = HandlerCompat.createAsync(Looper.getMainLooper()); } } return sHandler; } private  MainThreadAsyncHandler(); static Handler getInstance();  }
@Test public void canPostTaskToMainLooper() { Handler handler = MainThreadAsyncHandler.getInstance(); final AtomicBoolean didRun = new AtomicBoolean(false); handler.post(new Runnable() { @Override public void run() { didRun.set(true); } }); boolean ranBeforeTrigger = didRun.get(); ShadowLooper.runMainLooperOneTask(); boolean ranAfterTrigger = didRun.get(); assertThat(ranBeforeTrigger).isFalse(); assertThat(ranAfterTrigger).isTrue(); }
@Test @Config(minSdk = Build.VERSION_CODES.LOLLIPOP_MR1) public void sentMessageIsAsynchronous() { Message message = Message.obtain(); boolean isAsyncBeforeSending = message.isAsynchronous(); MainThreadAsyncHandler.getInstance().sendMessage(message); boolean isAsyncAfterSending = message.isAsynchronous(); assertThat(isAsyncBeforeSending).isFalse(); assertThat(isAsyncAfterSending).isTrue(); }