2011-07-17 15 views
10

Estoy tratando de recuperar los nombres de contacto dado el número de teléfono de contacto. Hice una función que debería funcionar en todas las versiones de API, por lo que no puedo hacer que funcione en 1.6 y no puedo ver el problema, tal vez alguien puede detectarlo.Obtener el nombre de contacto dado un número de teléfono en Android

Tenga en cuenta que he reemplazado las constantes de la API por cadenas, por lo que no tengo problemas de advertencia obsoletos.

public String getContactName(final String phoneNumber) 
{ 
    Uri uri; 
    String[] projection; 

    if (Build.VERSION.SDK_INT >= 5) 
    { 
     uri = Uri.parse("content://com.android.contacts/phone_lookup"); 
     projection = new String[] { "display_name" }; 
    } 
    else 
    { 
     uri = Uri.parse("content://contacts/phones/filter"); 
     projection = new String[] { "name" }; 
    } 

    uri = Uri.withAppendedPath(uri, Uri.encode(phoneNumber)); 
    Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null); 

    String contactName = ""; 

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

    cursor.close(); 
    cursor = null; 

    return contactName; 
} 
+1

No soporte 1.6 más! http://developer.android.com/resources/dashboard/platform-versions.html. Representa solo el 2,2% de la base de usuarios actual y ese número se reducirá, reducirá o disminuirá. Puede que nunca llegue a cero, pero eso es solo por rezagos tecnológicos que de todos modos no van a escuchar acerca de su nueva aplicación. No pierdas tu tiempo! –

+0

Para la comodidad de otros, he escrito una publicación que contiene todo el código para consultar el nombre, la foto, la identificación de contacto, etc. con una explicación decente. El código contiene fragmentos que se encuentran en diferentes respuestas, pero más organizados y probados. Enlace: http://hellafun.weebly.com/home/get-information-of-a-contact-from-number – Usman

Respuesta

9

Utilice reflexiones en lugar de comparar la versión sdk.

public String getContactName(final String phoneNumber) 
{ 
    Uri uri; 
    String[] projection; 
    mBaseUri = Contacts.Phones.CONTENT_FILTER_URL; 
    projection = new String[] { android.provider.Contacts.People.NAME }; 
    try { 
     Class<?> c =Class.forName("android.provider.ContactsContract$PhoneLookup"); 
     mBaseUri = (Uri) c.getField("CONTENT_FILTER_URI").get(mBaseUri); 
     projection = new String[] { "display_name" }; 
    } 
    catch (Exception e) { 
    } 


    uri = Uri.withAppendedPath(mBaseUri, Uri.encode(phoneNumber)); 
    Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null); 

    String contactName = ""; 

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

    cursor.close(); 
    cursor = null; 

    return contactName; 
} 
+0

Hola, probé algo similar, pero no funcionó. Aquí está mi pregunta, ¡realmente apreciaría su ayuda! :) http://stackoverflow.com/questions/35097844/get-contact-name/35098111#35098111 –

19

Esto parece funcionar bien en las últimas versiones:

private String getContactName(Context context, String number) { 

    String name = 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 != null) { 
     if (cursor.moveToFirst()) { 
      name =  cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME)); 
      Log.v(TAG, "Started uploadcontactphoto: Contact Found @ " + number);    
      Log.v(TAG, "Started uploadcontactphoto: Contact name = " + name); 
     } else { 
      Log.v(TAG, "Contact Not Found @ " + number); 
     } 
     cursor.close(); 
    } 
    return name; 
} 
+1

Gracias, funciona, pero si vas a obtener muchos nombres, debes hacerlo en asyncTask para evitar que no responda el error debido a mucha carga en el hilo principal. – Aziz

0
private String getContactNameFromNumber(String number) { 
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); 


Cursor cursor = context.getContentResolver().query(uri, new String[]{PhoneLookup.DISPLAY_NAME},null,null,null); 
if (cursor.moveToFirst()) 
{ 
    name = cursor.getString(cursor.getColumnIndex(PhoneLookup.D 
0
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; 
} 
Cuestiones relacionadas