Skip to content

Instantly share code, notes, and snippets.

@brskzr
Created December 4, 2020 08:42
Show Gist options
  • Select an option

  • Save brskzr/89dd623140e18ee65526f06cc902cf1c to your computer and use it in GitHub Desktop.

Select an option

Save brskzr/89dd623140e18ee65526f06cc902cf1c to your computer and use it in GitHub Desktop.

Revisions

  1. brskzr created this gist Dec 4, 2020.
    81 changes: 81 additions & 0 deletions EmojiUtils.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,81 @@
    package com.example.trainings

    import android.content.Context
    import android.util.Log
    import androidx.emoji.bundled.BundledEmojiCompatConfig
    import androidx.emoji.text.EmojiCompat
    import java.util.regex.Pattern

    object EmojiCompatUtils {

    private const val EMPTY_STRING = ""
    private const val REGEX_FOR_EMOJI = "\\\\u([0-9A-Fa-f]{4,5})\\b"

    private var isInitialized = false

    private var emojiCompatInitCallback : EmojiCompat.InitCallback = object: EmojiCompat.InitCallback() {
    override fun onInitialized() {
    super.onInitialized()
    setAsInitiliazed()
    }
    override fun onFailed(throwable: Throwable?) {
    super.onFailed(throwable)
    Log.e("EmojiCompatInit", "Failed to init EmojiCompat", throwable)
    }
    }

    @Synchronized
    private fun setAsInitiliazed() { isInitialized = true }

    fun init(context: Context){
    if(isInitialized) return

    val config: EmojiCompat.Config = BundledEmojiCompatConfig(context)
    EmojiCompat.init(config).registerInitCallback(emojiCompatInitCallback)
    }

    fun processSafely(sequence: CharSequence?): CharSequence {
    return sequence?.let {
    if (isInitialized) {
    try {
    return EmojiCompat.get().process(getUnicodeSupportedText(sequence.toString()))
    } catch (ex: Exception) {
    Log.e("EmojiCompatInit", "Failed to init EmojiCompat", ex)
    return sequence
    }
    } else {
    return removeEmojis(sequence.toString())
    }
    } ?: EMPTY_STRING
    }

    private fun getUnicodeSupportedText(text: String): String {
    return try {
    val pattern = Pattern.compile(REGEX_FOR_EMOJI)
    val sb = StringBuffer()
    val m = pattern.matcher(text)
    while (m.find()) {
    val cp = m.group(1).toInt(16)
    val added: String = if (cp < 0x10000) (cp as Char).toString() else String(intArrayOf(cp), 0, 1)
    m.appendReplacement(sb, added)
    }
    m.appendTail(sb)
    sb.toString()
    } catch (e: java.lang.Exception) {
    text
    }
    }

    private fun removeEmojis(text: String): CharSequence {
    return try {
    val pattern = Pattern.compile(REGEX_FOR_EMOJI)
    val sb = StringBuffer()
    val m = pattern.matcher(text)
    while (m.find()) { m.appendReplacement(sb, EMPTY_STRING) }
    m.appendTail(sb)
    sb.toString()
    } catch (e: java.lang.Exception) {
    text
    }
    }
    }