检查传入号码是存储在联系人列表中还是不存在于android中

Rav*_*ari 2 android android-contentprovider

在我的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;
}
Run Code Online (Sandbox Code Playgroud)

我有来自一个号码的来电+ 917878787878,但是在我的联系人中,这个联系人存储为名称XYZ,编号为78 78 787878,由于数字之间有空格而形成,并且还尝试排除+ 91但仍然返回null .那么我怎样才能找到以任何格式存储的号码.哪些号码可以与国家代码一起存储.

提前致谢.

Moh*_*Ali 6

请尝试使用此代码(使用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;
Run Code Online (Sandbox Code Playgroud)

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