android表情编码与解码

很多时候我们和服务器交互或者前端将文本保存到文件的时候,涉及一些带有表情符号的文本,因为存储的原因,要进行编码和解码过程,否则我们可能无法取出或者存入,或者是乱码。(一个简单的例子)

xml




    
    

Activity

//  Android表情符号的输入与取出
public class MainActivity extends AppCompatActivity{

    private EditText mInput;
    private Button mControl;
    private TextView mDisplay;
    private String mContent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initClick();
    }

    /**
     *初始化控件
     */
    private void initView() {
        mInput= (EditText) findViewById(R.id.input);
        mControl= (Button) findViewById(R.id.control);
        mDisplay= (TextView) findViewById(R.id.display);
    }

    /**
     * 点击事件
     */
    private void initClick() {
        mInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mContent=encode(s.toString());
                Log.e("TAG","---------"+mContent);
            }
        });
        //显示
        mControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDisplay.setText(decode(mContent));
            }
        });
    }

    /**
     * 将输入的内容编码
     * @param content
     * @return
     */
    public static String encode(String content) {
        StringBuilder sb = new StringBuilder(content.length() * 3);
        for (char c : content.toCharArray()) {
            if (c < 256) {
                sb.append(c);
            } else {
                sb.append("\\u");
                sb.append(Character.forDigit((c >>> 12) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 8) & 0xf, 16));
                sb.append(Character.forDigit((c >>> 4) & 0xf, 16));
                sb.append(Character.forDigit((c) & 0xf, 16));
            }
        }
        return sb.toString();
    }

    /**
     * 将取出内容解码
     * @param content
     * @return
     */
    public static String decode(String content) {
        final Pattern reUnicode = Pattern.compile("\\\\u([0-9a-zA-Z]{4})");
        Matcher sMatcher = reUnicode.matcher(content);
        StringBuffer sb = new StringBuffer(content.length());
        while (sMatcher.find()) {
            sMatcher.appendReplacement(sb,
                    Character.toString((char) Integer.parseInt(sMatcher.group(1), 16)));
        }
        sMatcher.appendTail(sb);
        return sb.toString();
    }
}


你可能感兴趣的:(android表情编码与解码)