alexbtr
alexbtr

Reputation: 3462

How to click Android phone "home" button programmatically in espresso

I need to simulate home button click in Espresso on Android phone. I tried

onView(withId(android.R.id.home)).perform(click());

and onView(withContentDescription("Navigate up")).perform(click());

as some posts suggested but it always fails to find the view. I'm new to Espresso and not sure how to debug it. Thanks.

Upvotes: 4

Views: 3213

Answers (1)

Mikhail Olshanski
Mikhail Olshanski

Reputation: 770

Better to use withContentDescription(R.string.abc_action_bar_up_description) rather than "Navigate up" but it doesn't act like a home button click anyway, it only uses the navigation bar's "back" button, so it would only work if you have it in your app.

If you want to simulate the home button click and you are using the UI Automator library, you can simulate it like this

fun pressHome() {
    // Might be a good idea to initialize it somewhere else
    val uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
    uiDevice.pressHome()
}

Alternatively, if you don't want to or can't use UI Automator, you might try calling Intrstumentation.sendKeyDownUpSync() with the KeyEvent.KEYCODE_HOME.

Upvotes: 7

Related Questions