Use the adb command to check if the keyboard has popped up or not.
adb shell dumpsys input_method | grep mInputShown
Exit: mShowRequested=true mShowExplicitlyRequested=false mShowForced=false mInputShown=true
if mInputShown=true , then a soft keyboard will appear. Then use driver.pressKeyCode(AndroidKeyCode.BACK);
PS: Please do not use driver.navigate().back() , as its behavior may not be the same on all devices.
source share