如何在将活动发送到后台后重新获得活动的访问权限

joe*_*cks 3 testing android android-espresso android-instrumentation

使用Espresso,我尝试使用Home按钮测试将活动发送到后台,然后再次将其放到前台进行一些检查:

@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()));
}
Run Code Online (Sandbox Code Playgroud)

我不得不使用intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);异常建议的,但除此之外我还测试了,启动它作为Launcher Activity,或使用 FLAG_ACTIVITY_REORDER_TO_FRONT,但视图不可见.即使测试通过.

joe*_*cks 8

好吧我明白了.首先,有必要使用getActivity提供的Activity Context,然后我可以使用Intents在后台和前台发送活动,使用HOME类和FLAG_ACTIVITY_REORDER_TO_FRONT:

private void goHome(Activity activity) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    activity.startActivity(intent);
}

private void bringToForeground(Activity activity) {
    Intent intent = new Intent(activity, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    activity.startActivity(intent);
}

@EspressoTest
public void test() {
    //do some ui stuff to ensure the activity is up and running
    goHome(getActivity());
    // eventually sleep, or implement an idling resource
    bringToForeground(getActivity());
    // do some ui tests
}
Run Code Online (Sandbox Code Playgroud)


And*_*ver 6

如果您要转到BackgroundByClickingHomeThenGetBackToTheApp,请考虑此响应,因为它可以100%起作用。

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

  • 只需添加两次调用`pressRecentApps()`即可使应用离开前台并在较短的时间内恢复 (3认同)
  • 在尝试恢复应用程序(最后一行)之前,我必须添加 `Thread.sleep(1500L)`。上面的答案和调用 `pressRecentApps()` 两次都适用于这个微小的变化。 (2认同)