Content Observer onChange method called twice after 1 change in cursor

前端 未结 5 1740
逝去的感伤
逝去的感伤 2020-12-30 03:11

I have an app in which I am hoping to send details in the android contact list to a remote server, so that the user can see his contacts online. To do this I want to notify

5条回答
  •  萌比男神i
    2020-12-30 03:45

    Consider how you register your observer. The second argument of registerContentObserver is boolean notifyForDescendents, you have set it to true. so you will be notified when either ContactsContract.Contacts.CONTENT_URI or any of its descandants uris were changed. It may be that some operation for contact with given id triggers notification both for the specific contact uri and global contacts uri - with second argument being true your observer observes both.

    Another thing is that You can register content observer for specific contact id uri - ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId). This however has nothing to do with your issue but registering separate observer for every contact looks rather ugly ;)

    Another suggestion: Maybe keep observer as final field not recreate it in onCreate (but only register it there).

    public class ContactService extends Service {
    
        private final ContentObserver contactsObserver = new ContentObserver(null) {
    
            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);    
                Log.i("LOG","detected change in contacts: "+selfChange);
    
                //your code here
            }
        };
    
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    
        @Override
        public void onCreate() {
    
            super.onCreate();
    
            getContentResolver().registerContentObserver(
                    ContactsContract.Contacts.CONTENT_URI, true, contactsObserver);   
        }
    
        @Override
        public void onDestroy() {
    
            getContentResolver().unregisterContentObserver(contactsObserver);
    
            super.onDestroy();
        }
    }
    

提交回复
热议问题