2

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

itaravika
  • 391
  • 1
  • 6
  • 17
  • Sync adapters can allow you to do this, http://developer.android.com/resources/samples/SampleSyncAdapter/index.html - it does however require the user to have sync enabled. – Jens Nov 07 '11 at 23:14

1 Answers1

1

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

josephus
  • 8,284
  • 1
  • 37
  • 57
  • could you get me an example of this? Thanks – itaravika Nov 07 '11 at 22:16
  • you're going to need a running service (or activity I guess) to have a content observer registered however. – Jens Nov 07 '11 at 23:15
  • this thread showed a very good example on how to make your own content observer http://stackoverflow.com/questions/1401280/how-to-listen-for-changes-in-contact-database – josephus Nov 08 '11 at 00:35