androidtestingandroid-espressoandroid-instrumentation

How to regain Access on a Activity after sending it to background


With Espresso I try to test sending an Activity to background, with the Home button and then getting it up in the foreground again to make some checks:

@EspressoTest
public void test() {
    onSomeView().check(matches(isDisplayed()));
    getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_HOME);

    Context context = getInstrumentation().getTargetContext();
    Intent intent = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);

    onSomeView().check(matches(isDisplayed()));
}

I had to use intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); which was suggested by an exception, but apart of that I also tested, starting it as the Launcher Activity, or using FLAG_ACTIVITY_REORDER_TO_FRONT, but the view is not visible. Even though the test passes.


Solution

  • Please consider this response as it works 100% when you want to goBackgroundByClickingHomeThenGetBackToTheApp.

    UiDevice device = UiDevice.getInstance(getInstrumentation());
            device.pressHome();
            device.pressRecentApps();
            device.findObject(new UiSelector().text(getTargetContext().getString(getTargetContext().getApplicationInfo().labelRes)))
                    .click();