Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 通訊錄開發:聯絡人搜尋功能的完整重構(中文、號碼、全拼、簡拼)

編輯:關於 Android 程式設計

先前寫過兩篇關於通訊錄搜尋的文章,方法都是從網上收集再自行試驗整理而來。但測試人員回報後發現仍有問題:部分簡拼搜不出來,或者簡拼轉換出錯。

問題根源:中文轉拼音本身就不好做

這件事的困難在於編碼與漢字的對應關係。以 GB2312 為例,它收錄 6763 個漢字並分為兩級:一級漢字 3755 個,二級漢字 3008 個。更麻煩的是這兩級的排序規則不同——一級漢字依拼音排序,二級漢字依筆畫排序。網路上流傳的許多「查表法」只涵蓋一級漢字,遇到二級漢字就完全失效,這正是簡拼搜不到的原因。

結論很明確:那類查表法無法滿足需求,必須換做法。以下是我目前負責的專案所採用的方案。

方案一:用 Android 內建的 HanziToPinyin 轉全拼

這個工具類來自 AOSP(Apache 2.0 授權),原本是 framework 為 CJK 輸入法準備的。它的實作思路與查表法有本質差異:用 Collator 做二分搜尋。

/**
 * 將中文字元轉為對應的拼音字串。
 * 對於有多種讀法的字,僅依 collator 順序選取其中一個(不支援多音字)。
 * 本實作以執行效能與記憶體為優先,代價是準確度上的妥協。
 * 高度依賴 zh_CN 的 ICU collation 資料,必須與 ICU 保持同步。
 */
public class HanziToPinyin {

    private static final String TAG = "HanziToPinyin";

    /** 已知拼音的第一個與最後一個漢字(依 zh collation 排序) */
    private static final String FIRST_PINYIN_UNIHAN = "\u963F";  // 阿
    private static final String LAST_PINYIN_UNIHAN  = "\u9FFF";

    private static final Collator COLLATOR = Collator.getInstance(Locale.CHINA);

    /**
     * UNIHANS:每個拼音在 collation 順序下的「代表字」。
     * PINYINS:與 UNIHANS 相同位移對應的拼音位元組陣列,
     *          以 ASCII 碼存放,0 作為結束標記。
     * (兩份對照表皆取自 ICU 4.6 的 zh.txt,篇幅過長此處省略,
     *   實際使用時直接引用 AOSP 的 HanziToPinyin.java 即可)
     */
    public static final char[] UNIHANS = { /* ... */ };
    public static final byte[][] PINYINS = { /* ... */ };

    private static HanziToPinyin sInstance;
    private final boolean mHasChinaCollator;

    public static class Token {
        public static final String SEPARATOR = " ";
        public static final int LATIN = 1;
        public static final int PINYIN = 2;
        public static final int UNKNOWN = 3;

        public int type;
        public String source;   // 轉換前的原字串
        public String target;   // 轉換後的結果(漢字為拼音,其餘為原字串)

        public Token() { }

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

    protected HanziToPinyin(boolean hasChinaCollator) {
        mHasChinaCollator = hasChinaCollator;
    }

    public static HanziToPinyin getInstance() {
        synchronized (HanziToPinyin.class) {
            if (sInstance != null) {
                return sInstance;
            }
            // 檢查系統是否具備 zh_CN 的 collation 資料
            final Locale[] locales = Collator.getAvailableLocales();
            for (Locale locale : locales) {
                if (locale.equals(Locale.CHINA)) {
                    sInstance = new HanziToPinyin(true);
                    return sInstance;
                }
            }
            Log.w(TAG, "There is no Chinese collator, HanziToPinyin is disabled");
            sInstance = new HanziToPinyin(false);
            return sInstance;
        }
    }

    /** 用 collator 的排序關係做二分搜尋,找出該字的拼音 */
    private Token getToken(char character) {
        Token token = new Token();
        String letter = Character.toString(character);
        token.source = letter;

        // ASCII 直接視為拉丁字元
        if (character < 256) {
            token.type = Token.LATIN;
            token.target = letter;
            return token;
        }

        // 用 collator 判斷是否落在漢字拼音區間內
        int cmp = COLLATOR.compare(letter, FIRST_PINYIN_UNIHAN);
        if (cmp < 0) {
            token.type = Token.UNKNOWN;
            token.target = letter;
            return token;
        } else if (cmp == 0) {
            token.type = Token.PINYIN;
            offset = 0;
        } else {
            cmp = COLLATOR.compare(letter, LAST_PINYIN_UNIHAN);
            if (cmp > 0) {
                token.type = Token.UNKNOWN;
                token.target = letter;
                return token;
            } else if (cmp == 0) {
                token.type = Token.PINYIN;
                offset = UNIHANS.length - 1;
            }
        }

        token.type = Token.PINYIN;
        if (offset < 0) {
            int begin = 0, end = UNIHANS.length - 1;
            while (begin <= end) {
                offset = (begin + end) / 2;
                String unihan = Character.toString(UNIHANS[offset]);
                cmp = COLLATOR.compare(letter, unihan);
                if (cmp == 0) {
                    break;
                } else if (cmp > 0) {
                    begin = offset + 1;
                } else {
                    end = offset - 1;
                }
            }
        }
        if (cmp < 0) {
            offset--;
        }

        StringBuilder pinyin = new StringBuilder();
        for (int j = 0; j < PINYINS[offset].length && PINYINS[offset][j] != 0; j++) {
            pinyin.append((char) PINYINS[offset][j]);
        }
        token.target = pinyin.toString();

        if (TextUtils.isEmpty(token.target)) {
            token.type = Token.UNKNOWN;
            token.target = token.source;
        }
        return token;
    }

    /**
     * 把輸入字串切成 token 序列。
     * 連續的 ASCII/未知字元會合併成一個 Token;
     * 每個有拼音的漢字各自成為一個 Token。
     * 若系統無中文 collator,回傳空陣列。
     */
    public ArrayList<Token> get(final String input) {
        ArrayList<Token> tokens = new ArrayList<Token>();
        if (!mHasChinaCollator || TextUtils.isEmpty(input)) {
            return tokens;
        }

        final int inputLength = input.length();
        final StringBuilder sb = new StringBuilder();
        int tokenType = Token.LATIN;

        for (int i = 0; i < inputLength; i++) {
            final char character = input.charAt(i);
            if (character == ' ') {
                if (sb.length() > 0) {
                    addToken(sb, tokens, tokenType);
                }
            } else if (character < 256) {
                if (tokenType != Token.LATIN && sb.length() > 0) {
                    addToken(sb, tokens, tokenType);
                }
                tokenType = Token.LATIN;
                sb.append(character);
            } else {
                Token t = getToken(character);
                if (t.type == Token.PINYIN) {
                    if (sb.length() > 0) {
                        addToken(sb, tokens, tokenType);
                    }
                    tokens.add(t);
                    tokenType = Token.PINYIN;
                } else {
                    if (tokenType != t.type && sb.length() > 0) {
                        addToken(sb, tokens, tokenType);
                    }
                    tokenType = t.type;
                    sb.append(character);
                }
            }
        }
        if (sb.length() > 0) {
            addToken(sb, tokens, tokenType);
        }
        return tokens;
    }

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

這個設計的關鍵在於:UNIHANS 表存的是「每個拼音的代表字」,而 lookup 用 Collator 比較而非硬查碼表。因為 ICU 的 zh collation 本身就把漢字依拼音排序,所以能在排序好的陣列上做二分搜尋,涵蓋率自然完整,不會有「二級漢字查不到」的問題。

取得全拼的包裝類別

package com.suntek.mobilemeeting.utils;

import java.util.ArrayList;
import com.suntek.mobilemeeting.utils.HanziToPinyin.Token;

/** 取得漢字拼音 */
public class PinYin {

    public static String getPinYin(String input) {
        ArrayList<Token> tokens = HanziToPinyin.getInstance().get(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().toLowerCase();
    }
}

方案二:簡拼(首字母)的處理

全拼有了,簡拼又是另一回事——使用者可能只打「zhangs」想搜「張三」。這裡用一份 GBK 編碼順序的對照字串,把漢字的 Unicode 位移映射到首字母:

/**
 * 依 GBK 漢字的 UNICODE 編碼取得漢字首字母。
 * GBK2UNICODE 為一長串以「a~z 依拼音排序」排列的代表字,
 * 與 Unicode 碼位 19968(\u4E00)起連續對應,此處基於篇幅省略。
 */
public class UnicodeGBK2Alpha {

    private static final String GBK2UNICODE = "YDYQSXMWZSSXJBYMGCCZ...";  // 省略

    /** 取得單字的 Unicode 碼位 */
    public static int getUnicodeFromGBK(String text) {
        int unicode = 0;
        if (text == null || text.length() <= 0) {
            return unicode;
        }
        String str = text.length() > 1 ? text.substring(0, 1) : text;
        try {
            // 用 "UnicodeLittle" 而非 "Unicode",
            // 因為部分 JRE 下 "Unicode" 的高低位元組順序不統一
            byte[] buff = str.getBytes("UnicodeLittle");
            unicode = (((int) (buff[3]) << 8) & 0xff00) + ((int) (buff[2]) & 0x00ff);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return unicode;
    }

    /** 取單字首字母;非漢字回傳空字串 */
    public static String getFirstCharOfString(String str) {
        String firstchar = "";
        int unicode = getUnicodeFromGBK(str);
        // 19968 ~ 40869 為 CJK 基本漢字區間
        if (unicode >= 19968 && unicode <= 40869) {
            firstchar = GBK2UNICODE.substring(unicode - 19968, unicode - 19968 + 1);
        }
        return firstchar.toLowerCase();
    }

    /** 取整串的拼音首字母,中間非字母符號保留 */
    public static String getSimpleCharsOfString(String str) {
        if (str == null) {
            return "";
        }
        StringBuilder chars = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            String firstchar = getFirstCharOfString(String.valueOf(str.charAt(i)));
            if (firstchar.length() <= 0) {
                firstchar = String.valueOf(str.charAt(i));   // 非漢字原樣保留
            }
            chars.append(firstchar);
        }
        return chars.toString();
    }

    /** 同上,但會把空白吃掉 */
    public static String getSimpleCharsOfStringByTrim(String str) {
        if (str == null) {
            return "";
        }
        StringBuilder chars = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            String firstchar = getFirstCharOfString(String.valueOf(str.charAt(i)));
            if (firstchar.length() <= 0) {
                if (str.charAt(i) != ' ') {
                    firstchar = String.valueOf(str.charAt(i));
                }
            }
            chars.append(firstchar);
        }
        return chars.toString();
    }
}

這份表是我目前用過效果最好的,基本沒發現明顯問題。它的依賴比較單純——只需要 JDK 內建的編碼轉換,不需要 ICU collator,因此在任何環境都能用。

把兩者組合成搜尋邏輯

/**
 * 依號碼/拼音搜尋聯絡人
 */
public static ArrayList<Contact> search(final String str,
                                        final ArrayList<Contact> allContacts) {
    ArrayList<Contact> contactList = new ArrayList<Contact>();

    // 以 0、1、+ 開頭視為號碼搜尋
    if (str.startsWith("0") || str.startsWith("1") || str.startsWith("+")) {
        for (Contact contact : allContacts) {
            if (contact.getNumber() != null && contact.getName() != null) {
                if (contact.getNumber().contains(str)
                        || contact.getName().contains(str)) {
                    contact.setGroup(str);
                    contactList.add(contact);
                }
            }
        }
        return contactList;
    }

    // 其餘情況先轉成拼音,再比對
    final String result = PinYin.getPinYin(str);
    for (Contact contact : allContacts) {
        if (contains(contact, result)) {
            contactList.add(contact);
        }
    }
    return contactList;
}

/**
 * 判斷聯絡人是否符合搜尋條件
 *
 * @param contact  待檢查的聯絡人
 * @param search   已轉為小寫拼音的搜尋字串
 */
public static boolean contains(Contact contact, String search) {
    if (TextUtils.isEmpty(contact.getName()) || TextUtils.isEmpty(search)) {
        return false;
    }

    boolean flag = false;

    // 1. 簡拼比對:搜尋字串較短(< 6)時才用首字母比對
    if (search.length() < 6) {
        String firstLetters = UnicodeGBK2Alpha.getSimpleCharsOfString(contact.getName());
        // 不區分大小寫,且要求「開頭相符」
        Pattern firstLetterMatcher =
                Pattern.compile("^" + search, Pattern.CASE_INSENSITIVE);
        flag = firstLetterMatcher.matcher(firstLetters).find();
    }

    // 2. 全拼比對:簡拼沒找到才用全拼
    if (!flag) {
        Pattern pattern = Pattern.compile(search, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(PinYin.getPinYin(contact.getName()));
        flag = matcher.find();
    }

    return flag;
}

為什麼要限制「搜尋字串 < 6」才用簡拼

這個判斷是刻意的。簡拼是「每個漢字取一個字母」,若使用者打了 6 個以上的字母,他顯然是在打全拼而非簡拼;此時再用首字母比對,反而容易誤中不相關的聯絡人。這條規則雖是啟發式的,實測下能明顯降低誤判。

幾個值得優化的地方

一、Regular Expression 有注入風險。使用者輸入 (、*、+ 等字元時,Pattern.compile() 會拋 PatternSyntaxException 造成崩潰。應該改用 Pattern.quote() 包起來,或乾脆不用 regex:

// 較安全的寫法
flag = firstLetters.toLowerCase().startsWith(search);

// 或
flag = Pattern.compile("^" + Pattern.quote(search),
                       Pattern.CASE_INSENSITIVE)
              .matcher(firstLetters).find();

二、簡拼比對用 startsWith 更合適。原本用 ^search 已是「開頭相符」,直接 startsWith 語意更清楚且不需 regex。

三、效能問題:每次搜尋都在反覆轉拼音。目前每輸入一個字,就會對所有聯絡人重新呼叫 getSimpleCharsOfString() 與 getPinYin()。聯絡人上千筆時會明顯卡頓。正確做法是在資料載入時預先計算並快取:

public class Contact {
    private String name;
    private String number;
    private String namePinyin;       // 預先算好的全拼
    private String nameInitials;     // 預先算好的簡拼

    public void prepareSearchIndex() {
        this.namePinyin = PinYin.getPinYin(name);
        this.nameInitials = UnicodeGBK2Alpha.getSimpleCharsOfString(name);
    }
}

這樣搜尋時就只是純字串比對,速度差距可達數十倍。

四、更好的方案:把拼音存進資料庫。搜尋完全可以直接在 SQL 層做,無論速度還是準確性都更有保障。做法是在建立聯絡人時把全拼與簡拼一起寫入自訂的索引表或 ContentProvider,再用 LIKE 'x%' 查詢,並善用索引。

五、注意線程問題。搜尋若跑在主執行緒,每次 keystroke 都觸發一次全量比對會造成 ANR。應放到背景執行緒,並加上 debounce(停止輸入約 200ms 後才搜尋)以及「取消前一次任務」的機制,避免舊結果覆蓋新結果。

小結

這篇記錄的是搜尋模組的實作,基本涵蓋中文、號碼、全拼、簡拼四種模糊比對。網路上很難找到通訊錄的完整實作,整理出來應該能讓有相同需求的人少走一些彎路。

當然這並非完美方案——不同專案需求各異,一開始設計時難免考慮不周。真正上線時,建議把拼音索引前置到資料層,並把搜尋移出主執行緒;這兩點才是影響使用者體感的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved