Xamarin forms check if keyboard is open or not

Xamarin.Android

[assembly: Xamarin.Forms.Dependency(typeof(Your.Android.Namespace.KeyboardService))]

namespace Your.Android.Namespace
{
  public class KeyboardService : IKeyboardService
  {
    public event EventHandler KeyboardIsShown;
    public event EventHandler KeyboardIsHidden;

    private InputMethodManager inputMethodManager;

    private bool wasShown = false;

    public KeyboardService()
    {
      GetInputMethodManager();
      SubscribeEvents();
    }

    public void OnGlobalLayout(object sender, EventArgs args)
    {
      GetInputMethodManager();
      if(!wasShown && IsCurrentlyShown())
      {
        KeyboardIsShown?.Invoke(this, EventArgs.Empty);
        wasShown = true;
      }
      else if(wasShown && !IsCurrentlyShown())
      {
        KeyboardIsHidden?.Invoke(this, EventArgs.Empty);
        wasShown = false;
      }
    }

    private bool IsCurrentlyShown()
    {
      return inputMethodManager.IsAcceptingText;
    }

    private void GetInputMethodManager()
    {
      if (inputMethodManager == null || inputMethodManager.Handle == IntPtr.Zero)
      {
        inputMethodManager = (InputMethodManager)this.GetSystemService(Context.InputMethodService);
      }
    }

    private void SubscribeEvents()
    {
      ((Activity)Xamarin.Forms.Forms.Context).Window.DecorView.ViewTreeObserver.GlobalLayout += this.OnGlobalLayout;
    }
  }
}


Xamarin.iOS

[assembly: Xamarin.Forms.Dependency(typeof(Your.iOS.Namespace.KeyboardService))]

namespace Your.iOS.Namespace
{
  public class KeyboardService : IKeyboardService
  {
    public event EventHandler KeyboardIsShown;
    public event EventHandler KeyboardIsHidden;

    public KeyboardService()
    {
      SubscribeEvents();
    }

    private void SubscribeEvents()
    {
      UIKeyboard.Notifications.ObserveDidShow(OnKeyboardDidShow);
      UIKeyboard.Notifications.ObserveDidHode(OnKeyboardDidHide);
    }

    private void OnKeyboardDidShow(object sender, EventArgs e)
    {
      KeyboardIsShown?.Invoke(this, EventArgs.Empty);
    }

    private void OnKeyboardDidHide(object sender, EventArgs e)
    {
      KeyboardIsHidden?.Invoke(this, EventArgs.Empty);
    }
  }
}


Xamarin Forms project

public interface IKeyboardService
{
  event EventHandler KeyboardIsShown;
  event EventHandler KeyboardIsHidden;
}


Xamarin Forms page

var keyboardService = Xamarin.Forms.DependencyService.Get<IKeyboardService>();