使用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()));
}
我不得不使用intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);这是一个异常所暗示的,但除此之外我还测试过,启动它作为启动器活动,或使用
FLAG_ACTIVITY_REORDER_TO_FRONT,但视图不可见.即使测试通过.
解决方法:
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();