Search code examples
androidandroid-uiautomator

UiDevice.getInstance failed with exception


I want to use the UiAutomator to click a button of a system pop-up window. So I added below code in one functin of my MainActivity class.

     device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

     device.wait(Until.hasObject(By.pkg("com.android.systemui").depth(0)), 2000);

     try {
         device.findObject(new UiSelector().textContains("START").className("android.widget.Button")).click();
     }
     catch (UiObjectNotFoundException e){
         e.printStackTrace();
     }

But when running the app, the console reported:

No instrumentation registered! Must run under a registering instrumentation at android.support.test.InstrumentationRegistry.getInstrumentation(InstrumentationRegistry.java:45)

Which part needs to be fixed ? I am new to Instrumentation. Thanks.


Solution

  • You need to obtain the Instrumentation from a test run from Android Studio or adb shell am instrument, not from a running app.