2010-10-20 21 views
1

我嘗試使用API​​ 2.x創建聯繫人,而不是舊聯繫人。這裏http://developer.android.com/guide/topics/providers/content-providers.html它只解釋了舊的API。我還沒有找到任何適當的教程,例子等,展示如何創建聯繫人。至於我已經想通了,我要創建一個原始的接觸,在接觸生我發現http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html從那裏我試圖使用API​​的Android:創建聯繫API 2.x

ContentValues values = new ContentValues(); 
values.put(RawContacts.ACCOUNT_TYPE, accountType); //accountType = "xxxx" 
values.put(RawContacts.ACCOUNT_NAME, accountName); //accountName = "aaaa" 
Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values); 
long rawContactId = ContentUris.parseId(rawContactUri); 
values.clear(); 
values.put(Data.RAW_CONTACT_ID, rawContactId); 
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); 
values.put(StructuredName.DISPLAY_NAME, "Mike Sullivan"); 
getContentResolver().insert(Data.CONTENT_URI, values); 

代碼的最後一行顯示「Data.CONTENT_URI」不能得到解決。這行代碼看起來有點用於1.6 API,我已將Data.CONTENT_URI更改爲ContactsContract.Data.CONTENT_URI。至少代碼編譯和執行,但我仍然沒有在我的地址簿中聯繫Mike Sullivan。我現在交換了以及「ContactsContract.Data」的其他「數據」仍然沒有變化。

有沒有人有一個簡單的例子如何在2.x地址簿中創建一個人?

編輯:我取得了一些進展,看起來我總是需要在手機上添加一個聯繫人的帳戶。我的手機帳戶類型爲com.google,帳戶名稱爲[email protected]。模擬器沒有任何東西。我想知道哪個帳戶需要添加我的聯繫人?我是否可以假設我總是隻有一個Gmail帳戶並使用此帳戶?

回答

0

你在找這樣的事嗎?

{ // insert a new data item 
    // first we need to get a raw contact corresponding to the contact. 
    Cursor rawCur = getContentResolver().query(RawContacts.CONTENT_URI, 
     new String[]{RawContacts._ID}, 
     RawContacts.CONTACT_ID + "=?", 
     new String[]{String.valueOf(contactId)}, null); 

    long rawContactId = -1; 
    for (boolean moreRaws = rawCur.moveToFirst(); moreRaws; 
     moreRaws = rawCur.moveToNext()) 
    { 
     rawContactId = rawCur.getLong(rawCur.getColumnIndex(RawContacts._ID)); 
    } 

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();  

    ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) 
     .withValue(ContactsContract.Data.RAW_CONTACT_ID, rawContactId) 
     .withValue(ContactsContract.Data.MIMETYPE, 
        ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) 
     .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,"y123-456-7890") 
      .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 
        ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME) 
     .build()); 

    try { 
     ContentProviderResult[] results = 
        getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); 
     logger.info("result: "+results[0]); 
    } catch (UnsupportedOperationException ex) { 
     ex.printStackTrace(); 
    } catch (RemoteException ex) { 
     ex.printStackTrace(); 
    } catch (OperationApplicationException ex) { 
     ex.printStackTrace(); 
    } 
    }