Domanda

Vorrei recuperare il nome di un contatto associato ad un numero telefonico in entrata.Mentre elaboro il numero in entrata nel broascastreceiver, avere una stringa con il nome del chiamante in entrata aiuterebbe molto il mio progetto.

Penserei che ciò implichi una query che utilizza la clausola SQL WHERE come filtro, ma devo ordinare i contatti?Un esempio o un suggerimento sarebbe di grande aiuto.

È stato utile?

Soluzione

Per questo è necessario utilizzare il provider PhoneLookup ottimizzato come descritto.

Aggiungi il permesso di AndroidManifest.xml:

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

Quindi:

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

Altri suggerimenti

Anche se questo è già stato risposto, ma qui è la funzione completa per ottenere il nome del contatto a partire dal numero. Spero che aiutare gli altri:

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

[ Aggiornamento in base a commento di Marcus]

Si dovrà chiedere questo permesso:

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

Questo è stato molto utile, ecco il mio codice finale per recuperare il nome del chiamante, id e foto:

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

... quindi basta fare quello che vuoi con "input" (il loro foto come un InputStream), "Nome", e "ContactID".

E qui ci sono i documenti che elencano le ~ 15 o giù di lì le colonne si ha accesso, basta aggiungere alla proiezione in prossimità della partenza del codice sopra:          http://developer.android.com/reference/android/provider/ContactsContract .PhoneLookup.html

Questa versione è la stessa risposta di Vikram.exe con il codice per evitare l'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();

}

Passa il numero di contatto da cui ricevi la chiamata nel seguente metodo.Questo metodo controllerà se il contatto è salvato sul tuo cellulare o meno.Se il contatto viene salvato, restituirà il nome del contatto, altrimenti restituirà una stringa con un numero sconosciuto

Aggiungi questo codice nella tua classe di ricevitore broadcast

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

per ottenere la visita del codice sorgente questo link

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top