How to select app fro recent apps in android Espresso Instrumentation Test

Viewed 292

How can I go to recent apps menu and How to select a particular app from the recents by using Espresso Android Instrumentation Test

2 Answers

Since selecting app from recent apps menu, it need controller over device. I think it can't be done with Espresso alone.

But you can achieve this by using android uiautomator.

     fun selectAppFromRecentApps(appTitle:String){
           mDevice.pressHome()
           mDevice.pressRecentApps()
           var uiSelector = UiSelector().className("android.widget.ScrollView") //scroll view listing all recent apps 
           var count = mDevice.findObject(uiSelector).childCount
           for (i in 0 until count step 1) {
               val child = UiScrollable(uiSelector.childSelector(UiSelector().resourceId("com.android.systemui:id/task_view_bar").instance(i))).getChild(UiSelector().resourceId("com.android.systemui:id/title")) // app framelayout
               val text = child.text
               if (text == appTitle) {
                   child.click()
                   break
               }
               if(i==count-1){
                   throw RuntimeException("App : "+ appTitle +" not found in 
                   recent apps")
               }
           }

         }

Unfortunately VIGNESHs answer did not work for me. I expect different devices to have different implementations of the overview view, or probably it's the Android version.

Anyway the following worked for me on different devices:

getInstrumentation().waitForIdleSync();
mDevice.pressHome();
mDevice.pressRecentApps();
mDevice.waitForIdle();
// If the application is listed, there needs to be an element with a content description
// containing the package name
if (!mDevice.wait(Until.hasObject(By.descStartsWith(getTargetContext().getPackageName())), 1000))
{
    fail("Overview did not open");
}
// As the app to be tested was the last one opened, we can simply press the button again.
mDevice.pressRecentApps();
// Wait until the activity under test is back.
// If you skip that, you might be to early, doing further tests.
mDevice.wait(Until.hasObject(By.pkg(getTargetContext().getPackageName())), 1000);
getInstrumentation().waitForIdleSync();
Related