Android notify when phone book is updated(Content Observer)

不羁岁月 提交于 2020-01-10 18:44:05

问题


I want to get a notification on my phone if there is any change in the contact database(add,delete).Right now i am using ContentObserver to get notified.Following is my code.Problem is that i able not able to know which contact is changed.Can anyone help???

public class ContentObserverActivity extends Activity {
    Button registerbutton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        registerbutton=(Button)findViewById(R.id.button1);
        registerbutton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            getContentResolver()
                .registerContentObserver(
                        ContactsContract.Contacts.CONTENT_URI, true,
                        new MyCOntentObserver());   
            }
        });
    }


    public class MyCOntentObserver extends ContentObserver{
        public MyCOntentObserver() {
            super(null);
        }
        @Override
        public void onChange(boolean selfChange) {
        super.onChange(selfChange);
            Log.e("","~~~~~~"+selfChange);
        }  

        @Override
        public boolean deliverSelfNotifications() {
            return true;
        }
    }
}

Thanks in advance.


回答1:


Observer does not provide the information that which contact is added/update/deleted. To get to know this save the contacts in your own DB table and when observer send the change notification check it with system's Contacts.




回答2:


I have changed onChange code to this.

@Override
public void onChange (boolean selfChange)
{
    this.onChange(selfChange, null);
}

@Override
public void onChange (boolean selfChange,Uri uri)
{
  Cursor cursor = mCntxt.getContentResolver().query(
            ContactsContract.Contacts.CONTENT_URI, null, null, null,ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP + " Desc");
    if (cursor.moveToNext()) {
        String id = cursor.getString(
                cursor.getColumnIndex(ContactsContract.Contacts._ID));
        String name = cursor.getString(
                cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        Log.w("Contact ID", id);
        Log.w("Person Name",name);
       }
}

Hope this helps..




回答3:


I think it may be possible using a Broadcast manager / receiver http://www.intertech.com/Blog/using-localbroadcastmanager-in-service-to-activity-communications/



来源:https://stackoverflow.com/questions/10426555/android-notify-when-phone-book-is-updatedcontent-observer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!