3

I'm playing around with UIAutomator/espresso and my application. Actually I would like to do the following:

  1. Do some action/check on my application

  2. Open the default browser to a URL

  3. Go back in my application and recheck the interface

Actually I can't manage to do the step 2. Here are the different way I tried:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://stackoverflow.com/"));

mActivityTestRule.launchActivity(browserIntent);
InstrumentationRegistry.getTargetContext().sendBroadcast(browserIntent);
InstrumentationRegistry.getInstrumentation().startActivitySync(browserIntent);

I searched on Stack Overflow but could not find the solution yet.

@LargeTest
@RunWith(AndroidJUnit4.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BackgroundForegroundTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

    private UiDevice mDevice;

    @Before
    public void before() {
        // Initialize UiDevice instance
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

        assertThat(mDevice, notNullValue());
    }

    @Test
    public void testOpenBrowserAndSwitchBack() throws InterruptedException {
        onView(withId(R.id.text1)).check(matches(isDisplayed()));

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://stackoverflow.com/"));
        mActivityTestRule.launchActivity(browserIntent);
        Thread.sleep(8000);

        getBackToApp("My App");

        onView(withId(R.id.text1)).check(matches(isDisplayed()));
    }

    private void getBackToApp(String appDescription){
        try {
            mDevice.pressRecentApps();
            UiSelector selector = new UiSelector();
            UiObject recentApp = mDevice.findObject(selector.descriptionContains(appDescription));
            recentApp.click();
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (UiObjectNotFoundException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
Zoe
  • 27,060
  • 21
  • 118
  • 148

1 Answers1

5

OK guys i figured it out. Here is the solution :

Context context = InstrumentationRegistry.getInstrumentation().getContext();
Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.android.chrome");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setData(Uri.parse("https://stackoverflow.com/"));
context.startActivity(intent);
mDevice.wait(Until.hasObject(By.pkg("com.android.chrome").depth(0)), TIMEOUT);