/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/publicstatic<T>TcheckNotNull(Treference){if(reference==null){thrownewNullPointerException();}returnreference;}
publicfinalclassSimpleCountingIdlingResourceimplementsIdlingResource{privatefinalStringmResourceName;privatefinalAtomicIntegercounter=newAtomicInteger(0);// written from main thread, read from any thread.
privatevolatileResourceCallbackresourceCallback;...// 省略其他不重要的代码
/**
* Increments the count of in-flight transactions to the resource being monitored.
*/publicvoidincrement(){counter.getAndIncrement();}/**
* Decrements the count of in-flight transactions to the resource being monitored.
*
* If this operation results in the counter falling below 0 - an exception is raised.
*
* @throws IllegalStateException if the counter is below 0.
*/publicvoiddecrement(){intcounterVal=counter.decrementAndGet();if(counterVal==0){// we've gone from non-zero to zero. That means we're idle now! Tell espresso.
if(null!=resourceCallback){resourceCallback.onTransitionToIdle();}}if(counterVal<0){thrownewIllegalArgumentException("Counter has been corrupted!");}}
/**
* Contains a static reference to {@link IdlingResource}, only available in the 'mock' build type.
*/publicclassEspressoIdlingResource{privatestaticfinalStringRESOURCE="GLOBAL";privatestaticSimpleCountingIdlingResourcemCountingIdlingResource=newSimpleCountingIdlingResource(RESOURCE);publicstaticvoidincrement(){mCountingIdlingResource.increment();}publicstaticvoiddecrement(){mCountingIdlingResource.decrement();}publicstaticIdlingResourcegetIdlingResource(){returnmCountingIdlingResource;}}
可以看出 EspressoIdlingResource 使用了 SimpleCountingIdlingResource 的功能实现了一个针对全局资源的空闲状态检查类。这是因为编写 app 的程序员知道:这个 app 中使用后台任务访问资源的行为都集中在 Model 层的数据获取行为,而 Model 层获取数据时使用的资源辅助类都是全局可用的(虽然其他层根本不会使用它)。
具体的使用方法也很简单: