2014-01-07 11:18:08 将百度空间里的东西移过来。
1. Save contact
我们前面已经写了四篇文章,做了大量的铺垫,总算到了这一步,见证奇迹的时刻终于到了。
用户添加了所有需要添加的信息后,点击“Done”来保存新建好的联系人,我们就从用户点击“Done”Button开始分析。
前面提到过,“Done”的处理事件是在ContactEditorActivity里面设置的,如下:
View saveMenuItem = customActionBarView.findViewById(R.id.save_menu_item);
saveMenuItem.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mFragment.doSaveAction();
}
});
我们进入ContactEditorFragment,看他的调用逻辑,doSaveAction()-->save(SaveMode.CLOSE),重点看save()方法:
public boolean save(int saveMode) {
...
// Save contact
Intent intent = ContactSaveService.createSaveContactIntent(
mContext, mState,
SAVE_MODE_EXTRA_KEY, saveMode, isEditingUserProfile(),
getActivity().getClass(),
ContactEditorActivity.ACTION_SAVE_COMPLETED,
mUpdatedPhotos, mPbrIndex);
mContext.startService(intent);
}
可以看到,我们千里追踪的mState被当作参数,和其他对象一样,进入了ContactSaveService,这个ContactSaveService继承自IntentService,进入ContactSaveService之后调用了一个回调方法,如下:
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_SAVE_CONTACT.equals(action)) {
saveContact(intent);
CallerInfoCacheUtils.sendUpdateCallerInfoCacheIntent(this);
}
看saveContact(intent),这个方法就是保存联系人的终极方法:
private void saveContact(Intent intent) {
RawContactDeltaList state = intent.getParcelableExtra(EXTRA_CONTACT_STATE);
final boolean isProfile = intent.getBooleanExtra(EXTRA_SAVE_IS_PROFILE, false);
Bundle updatedPhotos = intent.getParcelableExtra(EXTRA_UPDATED_PHOTOS); final AccountTypeManager accountTypes = AccountTypeManager.getInstance(this); String sourceId = null;
boolean isNewAdnContact = false;
RawContactDelta entityDelta = state.get(0);
final AccountType type = entityDelta.getAccountType(accountTypes); RawContactModifier.trimEmpty(state, accountTypes, isProfile); Uri lookupUri = null; final ContentResolver resolver = getContentResolver();
boolean succeeded = false; long insertedRawContactId = -1; int tries = 0;
while (tries++ < PERSIST_TRIES) {
final ArrayList<ContentProviderOperation> diff = state.buildDiff(); ContentProviderResult[] results = null;
if (!diff.isEmpty()) {
results = resolver.applyBatch(ContactsContract.AUTHORITY, diff);
}
final long rawContactId = getRawContactId(state, diff, results);
if (rawContactId == -1) {
}
insertedRawContactId = getInsertedRawContactId(diff, results);
final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
lookupUri = RawContacts.getContactLookupUri(resolver, rawContactUri);
succeeded = true; if (isAdnContact && isNewAdnContact && lookupUri != null) {
long contactId = ContentUris.parseId(lookupUri);
long newRawContactId = getRawContactId(state, diff, results);
AdnContactsCollector.updateAdnContactsNow(
contactId, newRawContactId,
entityDelta.getAccountType(),
entityDelta.getAccountName(), sourceId);
}
break;
}
reportSaveStatus(intent, lookupUri, succeeded);
}
上面的方法并非是完整的方法,我只是截取了重点代码,看while循环,说明会try保存联系人三次,而不是一次。我们前面一致关注的state = intent.getParcelableExtra(EXTRA_CONTACT_STATE);同时还从intent中取出了账户信息等,而最关键的代码实在while循环里面,首先看final ArrayList<ContentProviderOperation> diff = state.buildDiff();我们知道,保存联系人时一般会把所有的信息封装到ContentProviderOperation里面(可以参考http://www.cnblogs.com/wlrhnh/p/3477216.html 和 http://www.cnblogs.com/wlrhnh/p/3477252.html),然后执行resolver.applyBatch,那么现在的问题就是如何封装ContentProviderOperation了,我们知道state是RawContactDeltaList,而且根据前面的分析,它里面添加了一个RawContactDelta对象,下面我们进入RawContactDeltaList的state.buildDiff()方法:
public ArrayList<ContentProviderOperation> buildDiff() {
final ArrayList<ContentProviderOperation> diff = Lists.newArrayList(); for (RawContactDelta delta : this) {
final int firstBatch = diff.size();
final boolean isInsert = delta.isContactInsert();
backRefs[rawContactIndex++] = isInsert ? firstBatch : -1; delta.buildDiff(diff); if (mIsUnlinkingRawContact) continue; if (rawContactId != -1) {
final Builder builder = beginKeepTogether();
builder.withValue(AggregationExceptions.RAW_CONTACT_ID1, rawContactId);
builder.withValueBackReference(AggregationExceptions.RAW_CONTACT_ID2, firstBatch);
diff.add(builder.build()); } else if (firstInsertRow == -1) {
firstInsertRow = firstBatch; } else {
final Builder builder = beginKeepTogether();
builder.withValueBackReference(AggregationExceptions.RAW_CONTACT_ID1, firstInsertRow);
builder.withValueBackReference(AggregationExceptions.RAW_CONTACT_ID2, firstBatch);
diff.add(builder.build());
}
}
return diff;
}
首先for循环中取出了RawContactDelta对象,一般情况下只有一个,然后调用delta.buildDiff(diff),看来还得进入RawContactDelta的buildDiff()方法,此处传入的diff是一个ArrayList<ContentProviderOperation>对象:
for (ArrayList<ValuesDelta> mimeEntries : mEntries.values()) {
for (ValuesDelta child : mimeEntries) {
if (mContactsQueryUri.equals(Profile.CONTENT_RAW_CONTACTS_URI)) {
builder = child.buildDiff(Uri.withAppendedPath(Profile.CONTENT_URI, RawContacts.Data.CONTENT_DIRECTORY));
} else {
builder = child.buildDiff(Data.CONTENT_URI);
}
}
}
看外层的for循环,mEntries是HashMap<String, ArrayList<ValuesDelta>>对象,应该还记得前文中分析的saveValue(String column, String value)方法吧,如下:
protected void saveValue(String column, String value) {
Log.d("David", "column = " + column);
Log.d("David", "value = " + value);
mEntry.put(column, value);
Log.d("David", "mState = " + mState);
}
其中mEntry是ValuesDelta对象,而且有ValuesDelta entry : mState.getMimeEntries(mKind.mimeType)在KindSectionView.java。
继续分析内层循环,取出每一个ValuesDelta对象,然后调用child.buildDiff(Data.CONTENT_URI),进入ValuesDelta:
public ContentProviderOperation.Builder buildDiff(Uri targetUri) {
Builder builder = null;
if (isInsert()) {
mAfter.remove(mIdColumn);
builder = ContentProviderOperation.newInsert(targetUri);
builder.withValues(mAfter);
}
return builder;
}
好了,我们看这几个循环,我在每一循环下面都打了log:
RawContactDeltaList: for (RawContactDelta delta : this)
Log.d("D1", "delta = " + delta); RawContactDelta: for (ArrayList<ValuesDelta> mimeEntries : mEntries.values())
Log.d("D1", "===================================");
Log.d("D1", "mimeEntries = " + mimeEntries); RawContactDelta: for (ValuesDelta child : mimeEntries)
Log.d("D1", "child = " + child); ValuesDelta: buildDiff(Uri targetUri)
Log.d("D1", "mAfter = " + mAfter);
当我输入Name=Lucky, PhoneNumber=18611112222,然后点击保存联系人时,log结果如下:
RawContactDelta只有一个,包含所有用户输入的信息,可见RawContactDelta是一个包含所有联系人信息的对象;
每一个RawContactDelta都包含好几个ArrayList<ValuesDelta>,其实每一个ArrayList只有一个对象ValuesDelta;那么一个ValuesDelta包含一个Item的信息,如Name, Phone, Email。然后每一个ValuesDelta做buildDiff()操作,builder.withValues(mAfter),mAfter是一个ContentValues对象,打印结果如上图mAfter所示。
好了,现在返回到最开始的位置,ContactSaveService.java,saveContact()方法,有
final ArrayList<ContentProviderOperation> diff = state.buildDiff(); ContentProviderResult[] results = null;
if (!diff.isEmpty()) {
results = resolver.applyBatch(ContactsContract.AUTHORITY, diff);
}
resolver.applyBatch操作,那我们看看最终返回的diff是什么?
for (ContentProviderOperation d : diff) {
Log.d("D2", "ContentProviderOperation = " + d);
}
results = resolver.applyBatch(ContactsContract.AUTHORITY, diff);
log截图如下:
可以看到每一个ContentProviderOperation中都附带相应的值,而这些值会被resolver.applyBatch()方法保存在数据库里。
至此,新建联系人UI和保存联系人分析结束。