安卓的emoji表情转换为文字

由于安卓系统显示的emoji表情不那么好看,所以在项目的聊天里面使用了自己的图片代替了系统的emoji显示,但是问题来了,在收到消息通知的时候,通知栏并没有显示自定义的emoji显示,而是显示了系统的emoji表情,没办法,只好上网查一下解决方法,最终成功将emoji表情转化为“[表情]”。

关键方法如下:

    /**
     * 判别是否包含Emoji表情
     * 
     * @param str
     * @return
     */
    private static boolean containsEmoji(String str)
    {
        int len = str.length();
        for (int i = 0; i < len; i++)
        {
            if (isEmojiCharacter(str.charAt(i)))
            {
                return true;
            }
        }
        return false;
    }
    
    /**
     * 是否是emoji字符
     * 
     * @param codePoint
     * @return
     */
    private static boolean isEmojiCharacter(char codePoint)
    {
        return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }
    
     /**
     * 将含有EMOJI表情的文字转换
     * @param source
     * @return
     */
    public static String filterEmoji(String source)
    {
        if (!containsEmoji(source))
        {
            //不包含emoji就返回原字符串
            return source;
        }
        
        StringBuilder buf = null;
        //获取字符串的长度
        int len = source.length();
        //逐个检查字符,如果是emoji字符就替换为[表情]
        for (int i = 0; i < len; i++)
        {
            char codePoint = source.charAt(i);
            if (!isEmojiCharacter(codePoint))
            {
                if (buf == null)
                {
                    buf = new StringBuilder(source.length());
                }
                buf.append(codePoint);
            }
            else
            {
                if (buf == null)
                {
                    buf = new StringBuilder(source.length());
                }
                buf.append("[表情]");
            }
        }
        if (buf == null)
        {
            return "";
        }
        else
        {
            if (buf.length() == len)
            {
                buf = null;
                return source;
            }
            else
            {
                return buf.toString();
            }
        }
    }

本文章参考了:http://blog.csdn.net/zhengdan66/article/details/48276209

你可能感兴趣的:(安卓的emoji表情转换为文字)