查寻来电号码存储在联系人列表或不机器人机器人、或不、联系人、号码

2023-09-06 18:00:43 作者:孤独的造梦者

在我的Andr​​oid应用程序,当有来电我想告诉我的自定义用户界面,我能够做到这一点。 不,我要检查来电号码是从联系人与否。 下面是我的code这样做的,但它存储在我的联系人列表中的来电号码返回null。

In my android app when an incoming call i want to show my custom ui and i am able to do this. No i want to check incoming number is from contacts or not. Below is my code for doing so but it returns null for an incoming number which is stored in my contacts list.

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;
}

和我有来电从一些说,+ 917878787878但在我接触该联系人存储为XYZ名与数78 78 787878,这是由于格式化的数字排除+91但还是有space.and也尝试它返回null。 所以,我怎么能找到存储在任何format.Which可以存储与国家code或没有数字。

and i have incoming call from a number say+917878787878 but in my contacts this contact is stored as name XYZ with number 78 78 787878,which is formated because between number there are space.and also try by excluding +91 but still it returns null. So how can i find number which is stored in any format.Which may be stored with country code or not.

在此先感谢。

推荐答案

试试这个code,而不是(使用而不是电话PhoneLookup.CONTENT_FILTER_URI):

Try this code instead (using PhoneLookup.CONTENT_FILTER_URI instead of Phones):

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 :一个表再presents寻找了一个电话号码,例如来电显示的结果。要进行查找,你必须附加要找到CONTENT_FILTER_URI的数量。这个查询进行了高度优化。

As docs says ContactsContract.PhoneLookup: A table that represents the result of looking up a phone number, for example for caller ID. To perform a lookup you must append the number you want to find to CONTENT_FILTER_URI. This query is highly optimized.