KeyboardService

This is the core class for the creation of your own custom keyboard

The input method service class that can be extended to configure the keyboard behaviour, respond to keyboard requests and listen to keyboard events.

Notes:

  • The method createConfiguration will be invoked as soon as onCreate is invoked. Initialize any dependency needed by createConfiguration in onCreate before invoking super.onCreate. See example:
class CustomKeyboardService : KeyboardService() {
 
  var lateinit sharedPreferences: SharedPreferences
 
  override fun onCreate() {
    sharedPreferences = getSharedPreferences("default", MODE_PRIVATE)
    super.onCreate()
    eventBus.configuration.subscribe {
      when (it) {
        is AutoCorrectionChanged -> {
          sharedPreferences.edit().putBoolean(“autoCorrect”, it.enabled).apply()
        }
      }
    }
  }
 
  override val appIcon get() = R.drawable.ic_logo
 
  override fun createConfiguration() = 
    KeyboardConfiguration(
      typing = TypingConfiguration(
        autoCorrect = sharedPreferences.getBoolean(“autoCorrect”, true)
      ),
      style = StyleConfiguration(
        forceTheme = SystemThemes.lightTheme,
        forceDarkTheme = SystemThemes.darkTheme
      )
    )
}

Summary

Actions Description
createConfiguration Invoked when the keyboard requires a configuration
onAppsButtonClicked Invoked when the user clicks the app icon
reloadConfiguration Requests to reload the configuration
setUserWords Set words to the user dictionary
setInputValidator Set an input validator
updateFlaggedWords Sets a list of flagged words
appIcon Icon to be displayed on the top-left corner
configuration Retrieves the current keyboard configuration
eventBus Retrieves the EventBus instance

createConfiguration

open fun createConfiguration() : KeyboardConfiguration

Override this method to provide a custom configuration to the keyboard. See KeyboardConfiguration for details.

Notes:

  • When this method is not overridden, the default KeyboardConfiguration will be used.
  • This method will be invoked as soon as onCreate is invoked. Initialise any dependency needed by this method in onCreate before invoking super.onCreate.
  • This method will be invoked several times, including every time there is a window configuration change.

Example

var currentTheme = SystemThemes.lightTheme
 
override fun createConfiguration() = 
  KeyboardConfiguration(
    style = StyleConfiguration(
      forceTheme = currentTheme
    )
  )

onAppsButtonClicked

open fun onAppsButtonClicked()

Override this method to perform an action when the user taps the app icon.

Example:

override fun onAppsButtonClicked() {
  val intent = Intent(this, MainActivity::class.java)
  intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
  startActivity(intent)
}

reloadConfiguration

fun reloadConfiguration()

Call this method to reload the keyboard configuration. This will invoke the createConfiguration method.

Example:

var currentTheme = SystemThemes.lightTheme
 
private fun forceDarkTheme() {
  currentTheme = SystemThemes.darkTheme
  reloadConfiguration()
}

setUserWords

fun setUserWords(words: List<String>)

Set a list of words to be used as the user dictionary for the current configured language.

Notes:

  • Must be called after calling super.onCreate in the KeyboardService’s onCreate.
  • Should be called every time the language changes.

Example:

private fun setUserDictionary() {
    setUserWords(
        sharedPreferences.getStringSet(“userDictionary”, emptySet()).toList()
    )
}

setInputValidator

fun setInputValidator(validator: InputValidator?)

Sets an input validator for key taps and emojis. See InputValidator for details.

Example:

setInputValidator(object : InputValidator.DefaultInputValidator() {
    override fun validateInput(label: String, keyCode: Int) =
        when (label) {
            "\uD83D\uDD95" -> false
            "\uD83D\uDCA9" -> false
            else -> true
        }
})

updateFlaggedWords

fun updateFlaggedWords(locale: String, file: File, restartEngine: Boolean)

Updates the flagged words for a locale.

Notes:

  • This call is expensive, and should only be invoked the first time the keyboard is installed or when the flagged words file has been updated.
  • It must be called after super.onCreate has been invoked.
  • To apply the flagged words, the engine needs to restart. When updating several languages, it is more efficient to set the restartEngine flag only on the last file.
  • When flagged words are bundled as an asset, it must be copied to a location where the SDK has access (i.e. Context.filesDir)

Example:

override fun onCreate() {
  ...
  super.onCreate()
  ...
  updateFlaggedWordsFromAssets(“en-GB”, false)
  updateFlaggedWordsFromAssets(“en-US”, true)
  ...
}

private fun updateFlaggedWordsFromAssets(locale: String, restartEngine: Boolean) {
  val sharedPreferenceKey = “asset_flagged_$locale”
 
  if (!sharedPreferences.getBoolean(sharedPreferenceKey, false)) {
    val sourceAsset = "flagged/$locale.txt"
    val destination = File(filesDir, "flagged_words_$locale.txt")
 
    try {
      resources.assets.open(sourceAsset).apply {
        copyTo(FileOutputStream(destination))
        close()
      }
 
      updateFlaggedWords(locale, destination, restartEngine)
    } catch (exception: IOException) {
      Log.e("SampleKeyboard", "Error copying asset file: ${exception.message}")
    }
 
    sharedPreferences.edit().putBoolean(sharedPreferenceKey, true).apply()
  }
}

appIcon

open val appIcon : @DrawableRes Int?

Override this field’s getter to set the app icon displayed on the top left corner.

Notes:

  • When not overridden, it uses the default icon.
  • The icon will not be tinted with the current theme colorset.

Example:

override val appIcon get() = R.drawable.ic_logo

configuration

val configuration : KeyboardConfiguration

Retrieves the current configuration in use by the keyboard. See KeyboardConfiguration for details. This is a read-only field.

Example:

val lightTheme = SystemThemes.lightTheme
val darkTheme = SystemThemes.darkTheme
 
private fun switchTheme() {
  val wasLightTheme = configuration.style.forceTheme == lightTheme
  currentTheme = if (wasLightTheme) darkTheme else lightTheme
  reloadConfiguration()
}

eventBus

val eventBus : EventBus

Access the EventBus object in order to listen to keyboard events. See EventBus for details about the events emitted by the keyboard SDK.

Notes:

  • Read-only field
  • When there are no subscribers, the events will be discarded.
  • The subscription does not operate on any specific thread. It might be invoked from a different thread from the main thread.

Example:

private fun setupEvents() {
  eventBus.configuration.subscribe { 
    when (it) {
      is ConfigurationEvent.AutoCorrectionChanged -> {
        sharedPreferences.edit().putBoolean(“autoCorrect”, it.enabled).apply()
      } 
    }
  }
}

If something needs to be added or if you find an error in our documentation, please let us know either on our GitHub or Discord.

Last updated on March 31, 2022