【问题标题】:Check Incoming number is stored in Contacts list or not android检查来电号码是否存储在联系人列表中
【发布时间】:2014-11-11 07:00:00
【问题描述】:

在我的 android 应用程序中,当有来电时,我想显示我的自定义 ui 并且我能够做到这一点。 不,我想检查传入的号码是否来自联系人。 下面是我这样做的代码,但它为存储在我的联系人列表中的传入号码返回 null。

public String findNameByNumber(String num){
    Uri uri = Uri.withAppendedPath(Phones.CONTENT_FILTER_URL, Uri.encode(num));

    String name = null;
    Cursor cursor = mContext.getContentResolver().query(uri, 
                        new String[] { Phones.DISPLAY_NAME }, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
        name = cursor.getString(cursor.getColumnIndex(Phones.DISPLAY_NAME));
        cursor.close();
        callyName.setText(name+" Calling..");
    }
    return name;
}

我有来自一个号码say+917878787878的来电,但在我的联系人中,此联系人存储为名称XYZ,号码为78 78 787878,这是因为号码之间有空格而形成的。也可以尝试排除+91但仍然它返回空值。 那么我怎样才能找到以任何格式存储的号码。可能与国家代码一起存储或不存储。

提前致谢。

【问题讨论】:

    标签: android android-contentprovider


    【解决方案1】:

    试试这个代码(使用 PhoneLookup.CONTENT_FILTER_URI 代替电话):

    String res = null;
        try {
            ContentResolver resolver = ctx.getContentResolver();
            Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            Cursor c = resolver.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
    
            if (c != null) { // cursor not null means number is found contactsTable
                if (c.moveToFirst()) {   // so now find the contact Name
                    res = c.getString(c.getColumnIndex(CommonDataKinds.Phone.DISPLAY_NAME));
                }
                c.close();
            }
        } catch (Exception ex) {
            /* Ignore */
        }        
        return res;
    

    正如文档所说的ContactsContract.PhoneLookup:表示查找电话号码结果的表格,例如来电显示。要执行查找,您必须将要查找的数字附加到 CONTENT_FILTER_URI。此查询经过高度优化。

    【讨论】:

    • 我不知道为什么他们通过添加空格、括号()、破折号来格式化数字——这很烦人......有什么想法吗?
    • 不,先生,我没有,可能是因为他们想以特定格式显示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多