Run adb command - ‘adb shell dumpsys input_method | grep mInputShown
’
If you run on windows command prompt replace ‘grep’ with ‘FINDSTR’ . Output will be like this - “mShowRequested=false mShowExplicitlyRequested=false mShowForced=false mInputShown=false”
check mInputShown flag if true means keyboard is shown , then hide keyboard by driver.pressKeyCode(AndroidKeyCode.BACK);
appium API.