Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
alexbtr Avatar asked Mar 05 '23 15:03

alexbtr


1 Answers

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.

like image 89
Mikhail Olshanski Avatar answered Mar 30 '23 00:03

Mikhail Olshanski