Android:从电话号码中检索联系人姓名

发布于 2024-09-06 12:11:06 字数 136 浏览 7 评论 0原文

我想检索与来电号码关联的联系人姓名。当我处理广播接收器中的传入号码时,具有带有来电呼叫者姓名的字符串将极大地帮助我的项目。

我认为这涉及使用 sql WHERE 子句作为过滤器的查询,但我需要对联系人进行排序吗?一个例子或提示会有很大的帮助。

I would like to retrieve the name of a contact associated with an incoming telephone number. As I process the incoming number in the broascastreceiver having a String with the name of the incoming caller would help my project greatly.

I would think this involves a query using the sql WHERE clause as a filter, but do I need to sort the contacts? An example or hint would be of great assistance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

咋地 2024-09-13 12:11:06

虽然这个问题已经得到解答,但这里是从号码获取联系人姓名的完整功能。希望它能帮助其他人:

public static String getContactName(Context context, String phoneNumber) {
    ContentResolver cr = context.getContentResolver();
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
    if (cursor == null) {
        return null;
    }
    String contactName = null;
    if(cursor.moveToFirst()) {
        contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
    }

    if(cursor != null && !cursor.isClosed()) {
        cursor.close();
    }

    return contactName;
}

[根据 Marcus 的评论更新]

您必须请求此权限:

;

Although this has already been answered, but here is the complete function to get the contact name from number. Hope it will help others:

public static String getContactName(Context context, String phoneNumber) {
    ContentResolver cr = context.getContentResolver();
    Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
    Cursor cursor = cr.query(uri, new String[]{PhoneLookup.DISPLAY_NAME}, null, null, null);
    if (cursor == null) {
        return null;
    }
    String contactName = null;
    if(cursor.moveToFirst()) {
        contactName = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
    }

    if(cursor != null && !cursor.isClosed()) {
        cursor.close();
    }

    return contactName;
}

[Updating based on Marcus's comment]

You will have to ask for this permission:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

太傻旳人生 2024-09-13 12:11:06

为此,您需要使用所描述的优化的 PhoneLookup 提供程序。

将权限添加到AndroidManifest.xml

<uses-permission android:name="android.permission.READ_CONTACTS"/>

然后:

public String getContactName(final String phoneNumber, Context context)
{
    Uri uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));

    String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};

    String contactName="";
    Cursor cursor=context.getContentResolver().query(uri,projection,null,null,null);

    if (cursor != null) {
        if(cursor.moveToFirst()) {
            contactName=cursor.getString(0);
        }
        cursor.close();
    }

    return contactName;
}

For that you need to use the optimized PhoneLookup provider as described.

Add the permission to AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

Then:

public String getContactName(final String phoneNumber, Context context)
{
    Uri uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));

    String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME};

    String contactName="";
    Cursor cursor=context.getContentResolver().query(uri,projection,null,null,null);

    if (cursor != null) {
        if(cursor.moveToFirst()) {
            contactName=cursor.getString(0);
        }
        cursor.close();
    }

    return contactName;
}
七分※倦醒 2024-09-13 12:11:06

这非常有帮助,这是我用于检索呼叫者的姓名、id 和照片的最终代码:

private void uploadContactPhoto(Context context, String number) {

Log.v("ffnet", "Started uploadcontactphoto...");

String name = null;
String contactId = null;
InputStream input = null;

// define the columns I want the query to return
String[] projection = new String[] {
        ContactsContract.PhoneLookup.DISPLAY_NAME,
        ContactsContract.PhoneLookup._ID};

// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));

// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);

if (cursor.moveToFirst()) {

    // Get values from contacts database:
    contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
    name =      cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));

    // Get photo of contactId as input stream:
    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
    input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), uri);

    Log.v("ffnet", "Started uploadcontactphoto: Contact Found @ " + number);            
    Log.v("ffnet", "Started uploadcontactphoto: Contact name  = " + name);
    Log.v("ffnet", "Started uploadcontactphoto: Contact id    = " + contactId);

} else {

    Log.v("ffnet", "Started uploadcontactphoto: Contact Not Found @ " + number);
    return; // contact not found

}

// Only continue if we found a valid contact photo:
if (input == null) {
    Log.v("ffnet", "Started uploadcontactphoto: No photo found, id = " + contactId + " name = " + name);
    return; // no photo
} else {
    this.type = contactId;
    Log.v("ffnet", "Started uploadcontactphoto: Photo found, id = " + contactId + " name = " + name);
}

...然后只需使用“输入”(他们的照片作为输入流)、“姓名”和“contactId”执行您想要的操作。

以下是列出您有权访问的大约 15 列的文档,只需将它们添加到上面代码开头附近的投影即可:
http://developer.android.com/reference/android/provider/ContactsContract .PhoneLookup.html

This was very helpful, here's my final code for retrieving the caller's Name, id, and Photo:

private void uploadContactPhoto(Context context, String number) {

Log.v("ffnet", "Started uploadcontactphoto...");

String name = null;
String contactId = null;
InputStream input = null;

// define the columns I want the query to return
String[] projection = new String[] {
        ContactsContract.PhoneLookup.DISPLAY_NAME,
        ContactsContract.PhoneLookup._ID};

// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));

// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);

if (cursor.moveToFirst()) {

    // Get values from contacts database:
    contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
    name =      cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));

    // Get photo of contactId as input stream:
    Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
    input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), uri);

    Log.v("ffnet", "Started uploadcontactphoto: Contact Found @ " + number);            
    Log.v("ffnet", "Started uploadcontactphoto: Contact name  = " + name);
    Log.v("ffnet", "Started uploadcontactphoto: Contact id    = " + contactId);

} else {

    Log.v("ffnet", "Started uploadcontactphoto: Contact Not Found @ " + number);
    return; // contact not found

}

// Only continue if we found a valid contact photo:
if (input == null) {
    Log.v("ffnet", "Started uploadcontactphoto: No photo found, id = " + contactId + " name = " + name);
    return; // no photo
} else {
    this.type = contactId;
    Log.v("ffnet", "Started uploadcontactphoto: Photo found, id = " + contactId + " name = " + name);
}

... then just do whatever you want with "input" (their photo as an InputStream), "name", and "contactId".

And here are the docs listing the ~15 or so columns you have access to, just add them to the projection near the start of the code up above:
http://developer.android.com/reference/android/provider/ContactsContract.PhoneLookup.html

夏の忆 2024-09-13 12:11:06

此版本与 Vikram.exe 的答案相同,带有避免 ANR 的代码

interface GetContactNameListener {
    void contactName(String name);
}

public void getContactName(final String phoneNumber,final GetContactNameListener listener) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            ContentResolver cr = getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
            if (cursor == null) {
                return;
            }
            String contactName = null;
            if(cursor.moveToFirst()) {
                contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
            }

            if(cursor != null && !cursor.isClosed()) {
                cursor.close();
            }

            listener.contactName(contactName);
        }
    }).start();

}

This version is the same as Vikram.exe's answer with code to avoid the ANR

interface GetContactNameListener {
    void contactName(String name);
}

public void getContactName(final String phoneNumber,final GetContactNameListener listener) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            ContentResolver cr = getContentResolver();
            Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            Cursor cursor = cr.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
            if (cursor == null) {
                return;
            }
            String contactName = null;
            if(cursor.moveToFirst()) {
                contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
            }

            if(cursor != null && !cursor.isClosed()) {
                cursor.close();
            }

            listener.contactName(contactName);
        }
    }).start();

}
⒈起吃苦の倖褔 2024-09-13 12:11:06

通过以下方法传递您接到电话的联系号码。此方法将检查联系人是否保存在您的手机中。如果联系人已保存,则它将返回联系人姓名,否则将返回字符串未知数字

将此代码添加到您的广播接收器类中

    public String getContactDisplayNameByNumber(String number,Context context) {
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    name = "Incoming call from";

    ContentResolver contentResolver = context.getContentResolver();
    Cursor contactLookup = contentResolver.query(uri, null, null, null, null);

    try {
        if (contactLookup != null && contactLookup.getCount() > 0) {
            contactLookup.moveToNext();
            name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
            // this.id =
            // contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.CONTACT_ID));
            // String contactId =
            // contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
        }else{
            name = "Unknown number";
        }
    } finally {
        if (contactLookup != null) {
            contactLookup.close();
        }
    }

    return name;
}

以获取源代码访问 此链接

Pass the contact number from which you are getting the call in the following method. This Method will check whether the contact is saved in your mobile or not. If the contact is saved then it will return the contact name otherwise it return a string unknown number

Add this code in your Broadcast receiver class

    public String getContactDisplayNameByNumber(String number,Context context) {
    Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
    name = "Incoming call from";

    ContentResolver contentResolver = context.getContentResolver();
    Cursor contactLookup = contentResolver.query(uri, null, null, null, null);

    try {
        if (contactLookup != null && contactLookup.getCount() > 0) {
            contactLookup.moveToNext();
            name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
            // this.id =
            // contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.CONTACT_ID));
            // String contactId =
            // contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
        }else{
            name = "Unknown number";
        }
    } finally {
        if (contactLookup != null) {
            contactLookup.close();
        }
    }

    return name;
}

to get Source code visit this link

嘦怹 2024-09-13 12:11:06

为此,我们可以使用 PhoneLookup 提供程序通过手机号码获取姓名或联系方式。

将权限添加到 AndroidManifest.xml

<uses-permission android:name="android.permission.READ_CONTACTS"/>

在您的 Activity 中添加以下自定义 kotlin 方法,并使用所需的手机号码调用该方法。

fun getContactNameByPhoneNumber(context: Context, phoneNumber: String): String? {
        var phone = phoneNumber
        if(phoneNumber != null && phoneNumber.length > 0 && phoneNumber[0].equals('+'))
            phone = phoneNumber.substring(3)

        val projection = arrayOf(
            ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
        )
        val cursor = context.contentResolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection,
            ContactsContract.CommonDataKinds.Phone.NUMBER, null, null
        ) ?: return ""
        for (i in 0 until cursor.count) {
            cursor.moveToPosition(i)
            val nameFieldColumnIndex = cursor
                .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)
            val phoneFieldColumnIndex = cursor
                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

            if(phone.equals(cursor.getString(phoneFieldColumnIndex)))
                return cursor.getString(nameFieldColumnIndex)
        }
        return "Unknown"
    }

有关更多信息: https://developer.android.com/training/contacts-provider /检索名称

For that, we can use the PhoneLookup provider to get the names or contact details using the mobile number.

Add the permission to AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_CONTACTS"/>

Add the following custom kotlin method in your activity and call the same with the required mobile number.

fun getContactNameByPhoneNumber(context: Context, phoneNumber: String): String? {
        var phone = phoneNumber
        if(phoneNumber != null && phoneNumber.length > 0 && phoneNumber[0].equals('+'))
            phone = phoneNumber.substring(3)

        val projection = arrayOf(
            ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
        )
        val cursor = context.contentResolver.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            projection,
            ContactsContract.CommonDataKinds.Phone.NUMBER, null, null
        ) ?: return ""
        for (i in 0 until cursor.count) {
            cursor.moveToPosition(i)
            val nameFieldColumnIndex = cursor
                .getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)
            val phoneFieldColumnIndex = cursor
                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

            if(phone.equals(cursor.getString(phoneFieldColumnIndex)))
                return cursor.getString(nameFieldColumnIndex)
        }
        return "Unknown"
    }

For more: https://developer.android.com/training/contacts-provider/retrieve-names

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文