itaravika
itaravika

Reputation: 411

Android - Receive Contacts changes on telephone

Is it possible to have a broadcast receiver or service to be notified when a phone contact is added, deleted or modified?

I am making an application that needs fast access to phone contact, for what i was thinking of one copy sqlite phone contacts as accessed through contactsContracts.

If it's not possible, Does anyone know how to improve the response speed of the following code to see if a number is in the phone's contact list?

    public boolean isNumberInContacts(String Num){

    try {
        Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        while (cursor.moveToNext()) {
            String colID = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
            String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 

            if (Integer.parseInt(hasPhone)==1) {

                Cursor phone = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ colID,null, null); 

                for (int i=0;phone.moveToNext();i++){
                    if (Num.equals(mNumber.getNumber((phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)))))){
                        return true;                        
                    }
                }
            }
        }
        cursor.close();
    } catch (Exception e) { 
        e.printStackTrace(); 
        Log.d(TAG, "Error when validate number in contacts: "+ e.toString()); 
    }       
    return false;
}

Thanks

Upvotes: 2

Views: 1066

Answers (1)

josephus
josephus

Reputation: 8304

no broadcast when a contact is added. register a content observer in the contacts database to check for changes to it.

Upvotes: 1

Related Questions