3

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

我在 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();
4

1 回答 1

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;
    }
}
于 2014-07-14T09:57:48.437 回答