如何检测添加到联系人数据库的新联系人

时间:2013-04-17 23:32:59

标签: android contacts

如何检测添加到联系人数据库的新联系人

我在INTERNET上找到了很多代码,但是没有工作或包含错误......

有一个想法,而不是检测新联系人添加

的代码

我知道我的问题很难,但只是一个想法或一个简单的答案::)

我测试了这段代码,但它返回错误

ContentResolver cr = ctx.getContentResolver();

    String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME };

    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null,
            ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");

    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            Toast.makeText(this,cur.getString(cur.getColumnIndex(ContactsContract.Data._ID)), Toast.LENGTH_SHORT).show();
            Toast.makeText(this,cur.getString(cur.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)), Toast.LENGTH_SHORT).show();


        //  System.out.println(cur.getString(cur.getColumnIndex(ContactsContract.Data._ID)));
        //  System.out.println(cur.getString(cur.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)));      




        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                new String[]{ c.getId() }, null);

        while (pCur.moveToNext()) {

            Toast.makeText(this, "Start!", Toast.LENGTH_SHORT).show();
            System.out.println(.add(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
        } 
        pCur.close();

            Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
                    null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
                    new String[]{ c.getId() }, null); 

            while (emailCur.moveToNext()) { 
            System.out.println((emailCur.getString(
            emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
        }
        }
    }
    cur.close();

1 个答案:

答案 0 :(得分:1)

首先,您需要在主要活动中注册此接收器 -

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.d("onChange1", "~~~~~~" + selfChange);

        //getApplicationContext().startService(new Intent(MainActivity.this, SendContactService.class));
    }

    @Override
    public boolean deliverSelfNotifications() {
        Log.d("deliverSelfNotifications", "~~~~~~fg");
        return true;
    }
}