android 获取汉字拼音

由于前段时间项目需要,研究了下android各个版本中的汉字转拼音方法。

虽然Android系统本身自带有有将汉字转化为英文拼音的类和方法, 但是还没有对外开放接口, 需要把代码copy到项目中。其类为HanziToPinyin.Java,主要是在联系人应用中用到,但是在android中4.4版本(包含)和4.4之下的版本方法不一样。

直接上代码

android4.4之后的方法:

public class HanziToPinyinVL19{
   
    private static final String TAG = "HanziToPinyinVL19";
    private static HanziToPinyinVL19 sInstance;
    private Transliterator mPinyinTransliterator;
    private Transliterator mAsciiTransliterator;

    public static class Token {
   
        /**
         * Separator between target string for each source char
         */
        public static final String SEPARATOR = " ";
        public static final int LATIN = 1;
        public static final int PINYIN = 2;
        public static final int UNKNOWN = 3;

        public Token() {}

        public Token(int type, String source, String target) {
            this.type = type;
            this.source = source;
            this.target = target;
        }

        /**
         * Type of this token, ASCII, PINYIN or UNKNOWN.
         */
        public int type;
        /**
         * Original string before translation.
         */
        public String source;
        /**
         * Translated string of source. For Han, target is corresponding Pinyin. Otherwise target is
         * original string in source.
         */
        public String target;
    }

    private HanziToPinyinVL19() {
        try {
            mPinyinTransliterator = new Transliterator("Han-Latin/Names; Latin-Ascii; Any-Upper");
            mAsciiTransliterator = new Transliterator("Latin-Ascii");
        } catch (Exception e) {
            e.printStackTrace();
            Log.w(TAG, "Han-Latin/Names transliterator data is missing," + " HanziToPinyinVL19 is disabled");
        }
    }

    public boolean hasChineseTransliterator() {
        return mPinyinTransliterator != null;
    }

    public static HanziToPinyinVL19 getInstance() {
        synchronized (HanziToPinyinVL19.class) {
            if (sInstance == null) {
                sInstance = new HanziToPinyinVL19();
            }
            return sInstance;
        }
    }

    private void tokenize(char character, Token token) {
        token.source = Character.toString(character);
        // ASCII
        if (character < 128) {
            token.type = Token.LATIN;
            token.target = token.source;
            return;
        }
        // Extended Latin. Transcode these to ASCII equivalents
        if (character < 0x250 || (0x1e00 <= character && character < 0x1eff)) {
            token.type = Token.LATIN;
            token.target =
                    mAsciiTransliterator == null ? token.source : mAsciiTransliterator.transliterate(token.source);
            return;
        }
        token.type = Token.PINYIN;
        token.target = mPinyinTransliterator.transliterate(token.source);
        if (TextUtils.isEmpty(token.target) || TextUtils.equals(token.source, token.target)) {
            token.type = Token.UNKNOWN;
            token.target = token.source;
        }
    }

    @Nullable
    public String transliterate(final String input) {
        if (!hasChineseTransliterator() || TextUtils.isEmpty(input)) {
            return null;
        }
        return mPinyinTransliterator.transliterate(input);
    }

    /**
     * Convert the input to a array of tokens. The sequence of ASCII or Unknown characters without
     * space will be put into a Token, One Hanzi character which has pinyin will be treated as a
     * Token. If there is no Chinese transliterator, the empty token array is returned.
     */
    public ArrayList<Token> getTokens(final String input) {
        ArrayList<Token> tokens = new ArrayList<Token>();
        if (!hasChineseTransliterator() || TextUtils.isEmpty(input)) {
            // return empty tokens.
            return tokens;
        }
        final int inputLength = input.length();
        final StringBuilder sb = new StringBuilder();
        int tokenType = Token.LATIN;
        Token token = new Token();
        // Go through the input, create a new token when
        // a. Token type changed
        // b. Get the Pinyin of current charater.
        // c. current character is space.
        for (int i = 0; i < inputLength; i++) {
            final char character = input.charAt(i);
            if (Character.isSpaceChar(character)) {
                if (sb.length() > 0) {
                    addToken(sb, tokens, tokenType);
                }
            } else {
                tokenize(character, token);
                if (token.type == Token.PINYIN) {
                    if (sb.length() > 0) {
                        addToken(sb, tokens, tokenType);
                    }
                    tokens.add(token);
                    token = new Token();
                } else {
                    if (tokenType != token.type && sb.length() > 0) {
                        addToken(sb, tokens, tokenType);
                    }
                    sb.append(token.target);
                }
                tokenType = token.type;
            }
        }
        if (sb.length() > 0) {
            addToken(sb, tokens, tokenType);
        }
        return tokens;
    }


    private void addToken(final StringBuilder sb, final ArrayList<Token> tokens, final int tokenType) {
        String str = sb.toString();
        tokens.add(new Token(tokenType, str, str));
        sb.setLength(0);
    }

    public String transliterateByToken(String input) {
        ArrayList<Token> tokens = getTokens(input);
        StringBuilder sb = new StringBuilder();
        if (tokens != null && tokens.size() > 0) {
            for (Token token : tokens) {
                if (Token.PINYIN == token.type) {
                    sb.append(token.target);
                } else {
                    sb.append(token.source);
                }
            }
        }
        return sb.toString();
    }
}

由于4.4之后需要用到so文件,所以需要新建一个与系统一样的包名libcore.icu,里面新建Transliterator.java类:

package libcore.icu;

/**
 * Exposes icu4c's Transliterator.
 */
public final class Transliterator {
   
    private long peer;

    /**
     * Creates a new Transliterator for the given id.
     */
    public Transliterator(String id) {
        peer = create(id);
    }

    @Override
    protected synchronized void finalize() throws Throwable {
        try {
            destroy(peer);
            peer = 0;
        } finally {
            super.finalize();
        }
    }

    /**
     * Returns the ids of all known transliterators.
     */
    public static native String[] getAvailableIDs();

    /**
     * Transliterates the specified string.
     */
    public String transliterate(String s) {
        return transliterate(peer, s);
    }

    private static native long create(String id);

    private static native void destroy(long peer);

    private static native String transliterate(long peer, String s);
}

android4.4之下的方法:

源码路径:frameworks/base /core/java/com/android/internal/util/HanziToPinyin.java

import android.text.TextUtils;
import android.util.Log;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Locale;

/**
 * An object to convert Chinese character to its corresponding pinyin string. For characters with
 * multiple possible pinyin string, only one is selected according to collator. Polyphone is not
 * supported in this implementation. This class is implemented to achieve the best runtime
 * performance and minimum runtime resources with tolerable sacrifice of accuracy. This
 * implementation highly depends on zh_CN ICU collation data and must be always synchronized with
 * ICU.
 *
 * Currently this file is aligned to zh.txt in ICU 4.6 来自android4.2源码
 */

public class HanziToPinyinVL {
   
    private static final String TAG = "HanziToPinyin";
    // Turn on this flag when we want to check internal data structure.
    private static final boolean DEBUG = false;
    /**
     * Unihans array.
     *
     * Each unihans is the first one within same pinyin when collator is zh_CN.
     */
    public static final char[] UNIHANS = {
  '\u963f', '\u54ce', '\u5b89', '\u80ae', '\u51f9', '\u516b', '\u6300',
            '\u6273', '\u90a6', '\u52f9', '\u9642', '\u5954', '\u4f3b', '\u5c44', '\u8fb9', '\u706c', '\u618b',
            '\u6c43', '\u51ab', '\u7676', '\u5cec', '\u5693', '\u5072', '\u53c2', '\u4ed3', '\u64a1', '\u518a',
            '\u5d7e', '\u66fd', '\u66fe', '\u5c64', '\u53c9', '\u8286', '\u8fbf', '\u4f25', '\u6284', '\u8f66',
            '\u62bb', '\u6c88', '\u6c89', '\u9637', '\u5403', '\u5145', '\u62bd', '\u51fa', '\u6b3b', '\u63e3',
            '\u5ddb', '\u5205', '\u5439', '\u65fe', '\u9034', '\u5472', '\u5306', '\u51d1', '\u7c97', '\u6c46',
            '\u5d14', '\u90a8', '\u6413', '\u5491', '\u5446', '\u4e39', '\u5f53', '\u5200', '\u561a', '\u6265',
            '\u706f', '\u6c10', '\u55f2', '\u7538', '\u5201', '\u7239', '\u4e01', '\u4e1f', '\u4e1c', '\u543a',
            '\u53be', '\u8011', '\u8968', '\u5428', '\u591a', '\u59b8', '\u8bf6', '\u5940', '\u97a5', '\u513f',
            '\u53d1', '\u5e06', '\u531a', '\u98de', '\u5206', '\u4e30', '\u8985', '\u4ecf', '\u7d11', '\u4f15',
            '\u65ee', '\u4f85', '\u7518', '\u5188', '\u768b', '\u6208', '\u7ed9', '\u6839', '\u522f', '\u5de5',
            '\u52fe', '\u4f30', '\u74dc', '\u4e56', '\u5173', '\u5149', '\u5f52', '\u4e28', '\u5459', '\u54c8',
            '\u548d', '\u4f44', '\u592f', '\u8320', '\u8bc3', '\u9ed2', '\u62eb', '\u4ea8', '\u5677', '\u53ff',
            '\u9f41', '\u4e6f', '\u82b1', '\u6000', '\u72bf', '\u5ddf', '\u7070', '\u660f', '\u5419', '\u4e0c',
            '\u52a0', '\u620b', '\u6c5f', '\u827d', '\u9636', '\u5dfe', '\u5755', '\u5182', '\u4e29', '\u51e5',
            '\u59e2', '\u5658', '\u519b', '\u5494', '\u5f00', '\u520a', '\u5ffc', '\u5c3b', '\u533c', '\u808e',
            '\u52a5', '\u7a7a', '\u62a0', '\u625d', '\u5938', '\u84af', '\u5bbd', '\u5321', '\u4e8f', '\u5764',
            '\u6269', '\u5783', '\u6765', '\u5170', '\u5577', '\u635e', '\u808b', '\u52d2', '\u5d1a', '\u5215',
            '\u4fe9', '\u5941', '\u826f', '\u64a9', '\u5217', '\u62ce', '\u5222', '\u6e9c', '\u56d6', '\u9f99',
            '\u779c', '\u565c', '\u5a08', '\u7567', '\u62a1', '\u7f57', '\u5463', '\u5988', '\u57cb', '\u5ada',
            '\u7264', '\u732b', '\u4e48', '\u5445', '\u95e8', '\u753f', '\u54aa', '\u5b80', '\u55b5', '\u4e5c',
            '\u6c11', '\u540d', '\u8c2c', '\u6478', '\u54de', '\u6bea', '\u55ef', '\u62cf', '\u8149', '\u56e1',
            '\u56d4', '\u5b6c', '\u7592', '\u5a1e', '\u6041', '\u80fd', '\u59ae', '\u62c8', '\u5b22', '\u9e1f',
            '\u634f', '\u56dc', '\u5b81', '\u599e', '\u519c', '\u7fba', '\u5974', '\u597b', '\u759f', '\u9ec1',
            '\u90cd', '\u5594', '\u8bb4', '\u5991', '\u62cd', '\u7705', '\u4e53', '\u629b', '\u5478', '\u55b7',
            '\u5309', '\u4e15', '\u56e8', '\u527d', '\u6c15', '\u59d8', '\u4e52', '\u948b', '\u5256', '\u4ec6',
            '\u4e03', '\u6390', '\u5343', '\u545b', '\u6084', '\u767f', '\u4eb2', '\u72c5', '\u828e', '\u4e18',
            '\u533a', '\u5cd1', '\u7f3a', '\u590b', '\u5465', '\u7a63', '\u5a06', '\u60f9', '\u4eba', '\u6254',
            '\u65e5', '\u8338', '\u53b9', '\u909a', '\u633c', '\u5827
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值