suspendしてbackgroundに入る
これは簡単で、UiDevice#pressHome
を呼び出せばできます:
public static void enterBackground() {
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
device.pressHome();
}
resumeしてforegroundに戻る
UiDevice#pressRecentApps
でアプリ一覧を出して、そこでアプリケーションの表示名を探してclickします。
しかし、Recent AppsのUIレイアウトに依存するので、今後UIが変わった場合は対応する必要があります。下記の方法だと一応API14~API28までは動きます。
public static void enterForeground() throws Exception {
Context context = InstrumentationRegistry.getTargetContext();
UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
device.pressRecentApps();
UiObject object = device.findObject(new UiSelector().description(context.getString(context.getApplicationInfo().labelRes)));
object.click();
}
参考: