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

Android 通訊錄模糊搜尋實作:號碼、首拼、簡拼、全拼一次搞定

編輯:關於 Android 程式設計

實作通訊錄搜尋時,取得聯絡人的方式有好幾種,容易讓人眼花撩亂。以下提供一種依據 mimetypes 表來查詢、看起來較為簡潔的做法。

// 查詢所有聯絡人的姓名、電話、郵箱
public ArrayList<Contact> loadContacts() throws Exception {
    Uri uri = Uri.parse("content://com.android.contacts/contacts");
    ContentResolver resolver = this.getContentResolver();
    Cursor cursor = resolver.query(uri, new String[] { "_id" }, null, null, null);
    ArrayList<Contact> contacts = new ArrayList<Contact>();
    while (cursor.moveToNext()) {
        Contact contact = new Contact();
        int contractID = cursor.getInt(0);
        contact.setId(String.valueOf(contractID));
        uri = Uri.parse("content://com.android.contacts/contacts/" + contractID + "/data");
        Cursor cursor1 = resolver.query(uri, new String[] { "mimetype", "data1", "data2" }, null, null, null);
        while (cursor1.moveToNext()) {
            String data1 = cursor1.getString(cursor1.getColumnIndex("data1"));
            String mimeType = cursor1.getString(cursor1.getColumnIndex("mimetype"));
            if ("vnd.android.cursor.item/name".equals(mimeType)) {
                contact.setName(data1);           // 姓名
            } else if ("vnd.android.cursor.item/email_v2".equals(mimeType)) {
                if (!TextUtils.isEmpty(data1)) {  // 郵箱
                    contact.setEmail(data1);
                }
            } else if ("vnd.android.cursor.item/phone_v2".equals(mimeType)) {
                contact.setNumber(data1.replaceAll("-", "")); // 手機
            }
        }
        contacts.add(contact);
        cursor1.close();
    }
    cursor.close();
    return contacts;
}

關於模糊比對的取捨

最初我嘗試以正則表達式搭配第三方類庫 pinyin4j.jar 來實作,但实测效率偏低,當通訊錄數量龐大時明顯變慢,用體驗角度來看並不合適。於是改用自行實作的拼音轉換方式,速度立刻提升許多。

關鍵:中文轉拼音的工具類

網路上流傳的中文字元轉拼音實作類相当實用,核心是利用 GB2312 編碼的區位對照表,將每個中文字元映射到對應的拼音:

public class ChineseSpelling {
    private static int[] pyvalue = new int[] { -20319, -20317, -20304, -20295, ... };
    private static String[] pystr = new String[] { "a", "ai", "an", "ang", "ao", "ba", ... };
    private StringBuilder buffer;
    private String resource;
    private static ChineseSpelling chineseSpelling = new ChineseSpelling();

    public static ChineseSpelling getInstance() {
        return chineseSpelling;
    }

    public String getResource() {
        return resource;
    }

    public void setResource(String resource) {
        this.resource = resource;
    }

    private int getChsAscii(String chs) {
        int asc = 0;
        try {
            byte[] bytes = chs.getBytes("gb2312");
            if (bytes.length == 1) {          // 英文字元
                asc = bytes[0];
            }
            if (bytes.length == 2) {          // 中文字元
                int hightByte = 256 + bytes[0];
                int lowByte = 256 + bytes[1];
                asc = (256 * hightByte + lowByte) - 256 * 256;
            }
        } catch (Exception e) {
            System.out.println("ERROR:ChineseSpelling.class-getChsAscii(String chs)" + e);
        }
        return asc;
    }

    public String convert(String str) {
        String result = null;
        int ascii = getChsAscii(str);
        if (ascii > 0 && ascii < 160) {
            result = String.valueOf((char) ascii);
        } else {
            for (int i = (pyvalue.length - 1); i >= 0; i--) {
                if (pyvalue[i] <= ascii) {
                    result = pystr[i];
                    break;
                }
            }
        }
        return result;
    }

    public String getSelling(String chs) {
        String key, value;
        buffer = new StringBuilder();
        for (int i = 0; i < chs.length(); i++) {
            key = chs.substring(i, i + 1);
            if (key.getBytes().length >= 2) {
                value = convert(key);
                if (value == null) {
                    value = "unknown";
                }
            } else {
                value = key;
            }
            buffer.append(value);
        }
        return buffer.toString();
    }

    public String getSpelling() {
        return this.getSelling(this.getResource());
    }
}

整合搜尋邏輯

最後,把號碼搜尋與拼音搜尋整合在一起:以 0、1、+ 開頭時按號碼比對,中文則比對全拼,其餘則走簡拼比對。

public void search(String str) {
    contactList.clear();
    // 以 0 1 + 開頭則按號碼搜尋
    if (str.startsWith("0") || str.startsWith("1") || str.startsWith("+")) {
        for (Contact contact : allContacts) {
            if (contact.getNumber().contains(str)) {
                contact.setGroup(str);
                contactList.add(contact);
            }
        }
        refreshList();
        return;
    }
    boolean isChinese = false;
    Pattern pattern = Pattern.compile("[\\u4E00-\\u9FA5]");
    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        isChinese = true; // 為中文
    }
    for (Contact contact : allContacts) {
        if (contains(contact, str, isChinese)) {
            contactList.add(contact);
        } else if (contact.getNumber().contains(str)) {
            contact.setGroup(str);
            contactList.add(contact);
        }
    }
    refreshList();
}

public boolean contains(Contact contact, String search, boolean isChinese) {
    if (TextUtils.isEmpty(contact.getName())) {
        return false;
    }
    boolean flag = false;
    if (isChinese) {
        // 根據全拼中文查詢
        Pattern pattern = Pattern.compile(search.replace("-", ""), Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(contact.getName());
        return matcher.find();
    }
    // 簡拼比對
    ChineseSpelling finder = ChineseSpelling.getInstance();
    finder.setResource(contact.getName());
    Pattern pattern2 = Pattern.compile(search.toUpperCase(), Pattern.CASE_INSENSITIVE);
    Matcher matcher2 = pattern2.matcher(finder.getSpelling());
    flag = matcher2.find();
    return flag;
}

值得一提的是,中文在不同編碼下的位元組數並不相同:GBK 編碼的中文佔 2 個位元組,UTF-8 則佔 3 個。這個差異在動手實作編碼相關功能時特別容易踩坑,值得多加留意。

換上這套方法後,速度提升相當明顯,充分滿足了我的需求。雖說第三方類庫功能完善,但一旦牽涉到使用者體驗,就不得不權衡取捨——這正是本次實作最大的心得。

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