title: Run an instrument test from within app and wait for result
body: <p>I am developing a QA automation solution that can record/playback QA tests on Android. A key business requirement is to have no dependency on a connected PC while playing back the recorded test. To that end, I'm trying to run an Instrumentation test without a connected PC. (Specifically, an Appium UiAutomator2 test).</p>
  
  <p>My current approach is trying to run the test programmatically from my app. If I were running the test normally from a connected PC, I would use the command <code>adb shell am instrument -w</code>. I tried accessing ADB Shell from my app and running <code>am instrument -w</code>, but this produces an error that I am missing the INTERACT_ACROSS_USERS_FULL permission.</p>
  
  <p>To get around this issue, I am trying to run the test using <a href="https://developer.android.com/reference/android/content/Context.html#startInstrumentation(android.content.ComponentName,%20java.lang.String,%20android.os.Bundle)" rel="noreferrer">startInstrumentation</a>. This successfully starts the test. However, the test immediately crashes. Upon further investigation, I traced the crash to an NPE: the test is trying to retrieve <code>InstrumentationRegistry.getInstrumentation.getUiAutomation(0)</code>, but this returns null.</p>
  
  <p><strong>How do I run the test programatically and give it access to the required UiAutomation instance?</strong></p>
  
  <p>This is how I start the test:</p>
  
  <pre><code>public void runTest() {
      final String pm = getPackageName().replaceFirst(".test$", "");
      final InstrumentationInfo info = getInstrumentationInfo(pm);
      if (info != null) {
  
          final ComponentName cn = new ComponentName(info.packageName,
                  info.name);
  
          Bundle arguments = new Bundle();
          arguments.putString("class", "io.testim.appiumwrapper.test.AppiumUiAutomator2Server");
          //cn = {io.extension.test/android.support.test.runner.AndroidJUnitRunner}
          startInstrumentation(cn, null, arguments);
  
      } 
  }
  </code></pre>