2014-01-11 17:29:22

1. 当用户选择Phonebook中从SD卡导入联系人的操作后,程序回调转到ImportVCardActivity,然后用户选择好要导入的.vcf文件,并点击“确定”button,调用ImportVCardActivity中的importMultipleVCardFromExternalStorage()方法:

     private void importMultipleVCardFromExternalStorage(
final List<VCardFile> selectedVCardFileList) {
mHandler.post(new Runnable() {
public void run() {
mVCardReadThread = new VCardReadThread(selectedVCardFileList);
checkFinishingAndShowDialog(R.id.dialog_reading_vcard);
}
});
}

先new一个VCardReadThread对象,然后在onCreateDialog()-->getReadingVCardDialog()中start这个Thread,如下:

 private Dialog getReadingVCardDialog() {
if (mProgressDialogForReadVCard == null) {
String title = getString(R.string.spb_strings_import_all_txt);
String message = getString(R.string.reading_vcard_message);
mProgressDialogForReadVCard = new ProgressDialog(this);
mProgressDialogForReadVCard.setTitle(title);
mProgressDialogForReadVCard.setMessage(message);
mProgressDialogForReadVCard.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialogForReadVCard.setOnCancelListener(mVCardReadThread);
mProgressDialogForReadVCard.setCanceledOnTouchOutside(false);
mProgressDialogForReadVCard.setOnShowListener(new OnShowListener() {
public void onShow(DialogInterface dialog) {
if (mVCardReadThread != null) {
mVCardReadThread.start();
} else {
SpbLog.e(LOG_TAG, "mVCardReadThread is null");
dialog.dismiss();
mProgressDialogForReadVCard = null;
finish();
}
}
});
}
return mProgressDialogForReadVCard;
}

我们具体看VCardReadThread类的run()方法,以导入多个.vcf文件为例:

 // Read multiple files.
List<VCardFile> verifiedVCardFileList = new ArrayList<VCardFile>();
List<VCardSourceDetector> verifiedVCardFileDetector = new ArrayList<VCardSourceDetector>();
int count = 0;
for (VCardFile vcardFile : mSelectedVCardFileList) {
if (mCanceled) {
return;
}
VCardEntryCounter counter = new VCardEntryCounter();
VCardSourceDetector detector = new VCardSourceDetector();
VCardBuilderCollection builderCollection = new VCardBuilderCollection(
Arrays.asList(counter, detector));
Uri uri = vcardFile.getUri();
boolean result = false;
try {
result = readOneVCardFile(uri, VCardConfig.DEFAULT_CHARSET,
builderCollection, null, true, null, null);
}
if (result) {
count += counter.getCount();
verifiedVCardFileList.add(vcardFile);
verifiedVCardFileDetector.add(detector);
}
}
mProgressDialogForReadVCard.setProgressNumberFormat(
getString(R.string.spb_reading_contacts_txt));
mProgressDialogForReadVCard.setMax(count);
mProgressDialogForReadVCard.setProgress(0);
mProgressDialogForReadVCard.setIndeterminate(false); int i = 0;
for (VCardFile vcardFile : verifiedVCardFileList) {
if (mCanceled) {
return;
}
Uri uri = vcardFile.getUri();
doActuallyReadOneVCard(uri, mAccount, true, verifiedVCardFileDetector.get(i),
mErrorFileNameList);
i++;
}

有两个for循环,第一个是循环中获得了即将导入的联系人的总个数,因为这个信息要显示在ProgressBar进度条上,同时将vcardFile添加到verifiedVCardFileList中,这个List对象会在第二个循环中使用。再次我们先简单的看一下VCardFile是做什么的,代码如下:

 class VCardFile {
private String mName;
private Uri mUri;
private long mLastModified; public VCardFile(String name, Uri uri, long lastModified) {
mName = name;
mUri = uri;
mLastModified = lastModified;
} public String getName() {
return mName;
} public Uri getUri() {
return mUri;
} public long getLastModified() {
return mLastModified;
}
}

可以看到这个类的功能就是简单的封装.vcf File,包括对应的文件名称,uri以及最后一次修改时间。继续看第二个循环,其中调用了如下语句:

 doActuallyReadOneVCard(uri, mAccount, true, verifiedVCardFileDetector.get(i),
mErrorFileNameList);

传入了包含所有vcardFile的mErrorFileNameList, 帐号信息等,进入doActuallyReadOneVCard()方法:

 private boolean doActuallyReadOneVCard(Uri uri, Account account,
boolean showEntryParseProgress,
VCardSourceDetector detector, List<String> errorFileNameList) {
final Context context = ImportVCardActivity.this;
mProgressShower = null;
if (showEntryParseProgress) {
mProgressShower = new ProgressShower(mProgressDialogForReadVCard,
context.getString(R.string.reading_vcard_message),
ImportVCardActivity.this, mHandler);
mProgressShower.setListener(ImportVCardActivity.this);
}
mCommitter = new EntryCommitter(mResolver);
String estimatedCharset = detector.getEstimatedCharset();
VCardDataBuilder builder; // Use iso-8859-1 CHARSET to read VCard files, then use the charset
// inside the VCard files to decode special strings.
String targetCharset = estimatedCharset != null ? estimatedCharset : "utf-8";
String sourceCharset = "iso-8859-1";
if (try21) {
// the targetCharset parameter (2nd one) will have no effect if
// a CHARSET parameter is already provided in vcard. This is
// the default value if nothing better can be found.
builder = new VCardDataBuilder(sourceCharset, targetCharset, false, vcardType,
mAccount, mAccountType);
builder.addEntryHandler(mCommitter);
if (mProgressShower != null) {
builder.addEntryHandler(mProgressShower);
}
try {
VCardParser parser = new VCardParser_V21(detector);
parser.setBaseCharset(targetCharset);
if (readOneVCardFile(uri, sourceCharset, builder, detector, false,
parser, mErrorFileNameList)) {
getTestData().fileImportedOK(uri);
return true;
} else {
return false;
} }
} // NOT REACHED
return false;
}

我们的.vcf文件version是“VERSION:2.1”,targetCharset和sourceCharset使用来对.vcf文件进行编码的格式,这个方法中最重要的是调用了readOneVCardFile()方法,同时传入了VCardDataBuilder builder和VCardParser_V21 parser,这两个对象很重要,以后会重点用到。进入readOneVCardFile()方法,在这个方法中调用了callParser(parser, uri, charset, builder),如下:

 private void callParser(VCardParser parser, Uri uri, String charset,
VCardBuilder builder) throws IOException, VCardException {
mVCardParser = parser; if (mBrand == null) {
final String brand = Configuration.getInstance(ImportVCardActivity.this).getBrandName();
mBrand = brand != null ? brand : "";
}
mVCardParser.setBrand(mBrand);
InputStream is = null;
try {
is = mResolver.openInputStream(uri);
mVCardParser.parse(is, charset, builder, mCanceled);
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
// Failed to close input stream - do nothing
}
}
}

我们看到在这里将用流的方式访问.vcf文件,同时讲得到的流对象当作参数传给parse()方法,前面说过,mVCardParser是一个VCardParser_V21,所以进入VCardParser_V21看他的parse()方法,当然,他又调用了重载的parse(is, charset, builder),调用流程如下:

parse(is, charset, builder)-->parseVCardFile()-->parseOneVCard(firstReading)-->parseItems()-->parseItem(),如下:

 protected boolean parseItem() throws IOException, VCardException {
mEncoding = sDefaultEncoding; String line = getNonEmptyLine(); (1)
long start = System.currentTimeMillis(); mParamCharsetTmp = null;
String[] propertyNameAndValue = separateLineAndHandleGroup(line);
if (propertyNameAndValue == null) {
return true;
}
if (propertyNameAndValue.length != 2) {
throw new VCardInvalidLineException("Invalid line \"" + line + "\"");
}
String propertyName = propertyNameAndValue[0].toUpperCase(); (2)
String propertyValue = propertyNameAndValue[1]; mTimeParseLineAndHandleGroup += System.currentTimeMillis() - start; if (propertyName.equals("ADR") || propertyName.equals("ORG") ||
propertyName.equals("N")
// "SOUND" is not multi-part on vCard specification but mere assumption.
// Some Japanese phones use this as multi (DoCoMo spec).
|| propertyName.equals("SOUND")
) {
start = System.currentTimeMillis();
Log.d("D4", "propertyName = " + propertyName);
Log.d("D4", "propertyValue = " + propertyValue);
handleMultiplePropertyValue(propertyName, propertyValue); (3)
mTimeParseAdrOrgN += System.currentTimeMillis() - start;
return false;
} else if (propertyName.equals("AGENT")) {
handleAgent(propertyValue);
return false;
} else if (isValidPropertyName(propertyName)) {
if (propertyName.equals("BEGIN")) {
if (propertyValue.equals("VCARD")) {
throw new VCardNestedException("This vCard has nested vCard data in it.");
} else {
throw new VCardException("Unknown BEGIN type: " + propertyValue);
}
} else if (propertyName.equals("VERSION") && !propertyValue.equals(getVersion())) {
throw new VCardVersionException("Incompatible version: " +
propertyValue + " != " + getVersion());
}
start = System.currentTimeMillis();
handlePropertyValue(propertyName, propertyValue); (3)
mTimeParsePropertyValues += System.currentTimeMillis() - start;
return false;
} throw new VCardNotSupportedException("Unknown property name: \"" +
propertyName + "\"");
}

首先看(1)的代码,从流文件中读取一行,所以可以发现其实就是一行一行读取并解析.vcf文件的。看(2)的代码,取出来propertyName,然后根据propertyName来获得propertyValue,下面是一段log,

 D/D44444444444444444444444( 9909): propertyName = VERSION
D/D44444444444444444444444( 9909): propertyValue = 2.1
D/D42 ( 9909): propertyName = VERSION
D/D42 ( 9909): propertyValue = 2.1
D/D44444444444444444444444( 9909): propertyName = N
D/D44444444444444444444444( 9909): propertyValue = =E9=AD=8F=E4=BC=9F;;;;
D/D4 ( 9909): propertyName = N
D/D4 ( 9909): propertyValue = =E9=AD=8F=E4=BC=9F;;;;
D/D4 ( 9909): builder.toString().trim() =
D/D44444444444444444444444( 9909): propertyName = FN
D/D44444444444444444444444( 9909): propertyValue = =E9=AD=8F=E4=BC=9F
D/D42 ( 9909): propertyName = FN
D/D42 ( 9909): propertyValue = =E9=AD=8F=E4=BC=9F
D/D44444444444444444444444( 9909): propertyName = TEL
D/D44444444444444444444444( 9909): propertyValue = 18611976642
D/D42 ( 9909): propertyName = TEL
D/D42 ( 9909): propertyValue = 18611976642

而一个典型的.vcf文件,这个文件中只包含一个联系人,名字是**,号码是18611976642,如下:

 BEGIN:VCARD
VERSION:2.1
N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=E9=AD=8F=E4=BC=9F;;;;
FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=E9=AD=8F=E4=BC=9F
TEL;HOME;VOICE:18611976642
END:VCARD

这样就取到了联系人包含的所有信息。

在每一个判断语句块里都有一个方法,看(3)的代码,这两个方法最终都会调用mBuilder.propertyValues(v)将propertyValue值所在的list存起来,因此最终的解析工作也是在propertyValues()方法里完成的。下面再看一个更复杂的.vcf文件:

BEGIN:VCARD
VERSION:2.1
N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=E6=9D=A8=E9=A3=9E=E5=B9=B4;;;;
FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=E6=9D=A8=E9=A3=9E=E5=B9=B4
TEL;HOME;VOICE:18896784536
TEL;CELL:9999999999
EMAIL;HOME:[email protected]
PHOTO;ENCODING=BASE64;TYPE=JPEG:/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCA
gMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGB
IUFRT/2wBDAQMEBAUEBQkFBQkUDQsN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Y59xHIR+oFa/w/0waZ4H0S0AAENlCmB0HyA/1rnSsjTqZcsHneI
rtuvk2qL+LMx/8AZRRfW2WbH0FaenW/napqkvUfaFjGfRUXP6k1HdhIx8zKn1OKOXSw0cdqNm
SCeTXMX1sUJOOldnqeoWUAbzLqFMf7Yrhdf8XaHalg+oQrjuGrBw1GmZV2AvfpxWBqcyQQu7t
tVeSxrP1r4veFbQtv1SE/RwK8N+Jvxt+06ikGkzLcWDACQDrjnIz/AJ61rCk5PQnnsbPiPW7r
xzqM2laXJ5FlEdk91/MD3/z9cPxZpOn6H4YvtPtdnmm2bMhPL/Mo69f/AK1ZrfFXQNOjK2NnL
zyxXIDH8a4/XviCmrLfRpZkR3ESogdvuOCfm/EEiuqFN3tYxctDK8TQ6Quk6fY2Du93brvbcM
HkDJPoRgE/Q1heRKmqyxT/APEv1G3bAWMEYcE5H+fWorXzbW5a4YefIRtzIexGP5VLfXN1qM8
U8rBp0QR7xyWAHGfw4rVU3shcyP/Z

这个联系人信息如下:

Phonebook 导入SD上的.vcf联系人-LMLPHP

可以发现,中文姓名和头像是进行了编码的,其他比如phone number,email等直接文本保存,那么我们进入propertyValues()方法看一下姓名和头像是怎么解析的,前面说过VCardDataBuilder mBuilder很重要,那么当然propertyValues()方法也是在VCardDataBuilder里面喽,代码如下:

     public void propertyValues(List<String> values) {
if (values == null || values.size() == 0) {
return;
} final Collection<String> charsetCollection = mCurrentProperty.getParameters("CHARSET");
String charset =
((charsetCollection != null) ? charsetCollection.iterator().next() : null);
String targetCharset = CharsetUtils.nameForDefaultVendor(charset); final Collection<String> encodingCollection = mCurrentProperty.getParameters("ENCODING");
String encoding =
((encodingCollection != null) ? encodingCollection.iterator().next() : null); if (targetCharset == null || targetCharset.length() == 0) {
targetCharset = mTargetCharset;
} if (!Charset.isSupported(targetCharset)
&& (("shift_jis").equalsIgnoreCase(charset)
|| "shift-jis".equalsIgnoreCase(charset)
|| "sjis".equalsIgnoreCase(charset))) {
Log.w(LOG_TAG, targetCharset + " is not supported. Use shif_jis encoding.");
targetCharset = "shift_jis";
} for (String value : values) {
Log.d("D2D", "value = " + value);
Log.d("D2D", "handleOneValue(value, targetCharset, encoding) = " + handleOneValue(value, targetCharset, encoding));
mCurrentProperty.addToPropertyValueList(
handleOneValue(value, targetCharset, encoding));
}
}

以杨飞年为例,导入只包含他的信息的.vcf文件,看log如下:

D/D2D     (11785): value = 2.1
D/D2D (11785): handleOneValue(value, targetCharset, encoding) = 2.1
D/D2D (11785): value = =E6=9D=A8=E9=A3=9E=E5=B9=B4
D/D2D (11785): handleOneValue(value, targetCharset, encoding) = 杨飞年
D/D2D (11785): value =
D/D2D (11785): handleOneValue(value, targetCharset, encoding) =
D/D2D (11785): value =
D/D2D (11785): handleOneValue(value, targetCharset, encoding) =
D/D2D (11785): value =
D/D2D (11785): handleOneValue(value, targetCharset, encoding) =
D/D2D (11785): value =
D/D2D (11785): handleOneValue(value, targetCharset, encoding) =
D/D2D (11785): value = =E6=9D=A8=E9=A3=9E=E5=B9=B4
D/D2D (11785): handleOneValue(value, targetCharset, encoding) = 杨飞年
D/D2D (11785): value = 18896784536
D/D2D (11785): handleOneValue(value, targetCharset, encoding) = 18896784536
D/D2D (11785): value = 9999999999
D/D2D (11785): handleOneValue(value, targetCharset, encoding) = 9999999999
D/D2D (11785): value = [email protected]
D/D2D (11785): handleOneValue(value, targetCharset, encoding) = [email protected]
D/D2D (11785): value = /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBA QIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDA kKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo KCgoKCgoKCgoKCgoKCgoKCgr/wAARCABgAGADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAA AAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQI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XPaPc31tcy2YTcv3l/u7f71Yy5OTlN4w/lP2A+APivQvFngZvGumFfJ1GCO eDcyttXbu2t/tfNXf8AgvxZYeHfC1xquoXar5Nl9ob/AGWbc1fmv8BI/wBr3wt8KLL4hfCjUv 7Q0bUpZoH01X+ZZFkZW+VvvL8u7/gVdX4o/b5+KsXh3U/A3jX4c3FjdxpGt2yqy7o/u7f9nd9 2uOFP3vdZpJykfuzrMjzBUd23722sv3mX5q8g+IF0+v8A7enhXTHdn/4Rnwbq15/e2+Z5cK/+ k9euF3bUIkfaVaVUi/76rxrw43/CW/t3eMtZ2Ns03wfY2O7+7515PM3/AI7ItKAj2jxXry6B4 X1DUA7FbOykZdv+yrVn/Du7/snwBYaaJNph0u3i2/7W1f8A4lqw/i7fhPA19amT5rzy7VF/66 SLH/7NUw1eOHTjDHJyjLs/3VX/AOyohyxkNHpfgjUke4+yzz/upP8AWqw/h2tXA/tBaR8GYPg H40+IN5q0dnPpOhyfatJZPlv

将“=E6=9D=A8=E9=A3=9E=E5=B9=B4”解析成了“杨飞年”,至于头像,好像还是一堆编码,继续看。

调用了mCurrentProperty.addToPropertyValueList()方法,代码在ContactStruct.java,如下:

 public void addToPropertyValueList(String propertyValue) {
// Trim trailing nul-chars, could be present if the value
// originally originated from a SIM.
propertyValue = StringUtil.trimTrailingNul(propertyValue); if (propertyValue != null) {
mPropertyValueList.add(propertyValue.replace("\r\n", "\n"));
}
}

很简单,只是将传进来的propertyValue保存到List<String> mPropertyValueList对象中,到此,我们发现所有联系人相关的信息其实最后都会保存在mPropertyValueList中,也就是说,将以个联系人信息从.vcf文件中读入、解析之后保存到这里,那么最后一个问题就是什么时候将解析后的联系人信息保存到数据库的呢?

还记得我们前面有提到这样的调用流程:

parse(is, charset, builder)-->parseVCardFile()-->parseOneVCard(firstReading)-->parseItems()-->parseItem()

其中调用了parseOneVCard(firstReading)方法,代码如下:

     private boolean parseOneVCard(boolean firstReading) throws IOException, VCardException {
boolean allowGarbage = false;
if (firstReading) {
if (mNestCount > 0) {
for (int i = 0; i < mNestCount; i++) {
if (!readBeginVCard(allowGarbage)) {
return false;
}
allowGarbage = true;
}
}
} // Allow garbage lines before "BEGIN:VCARD" at any time.
// Some of the vCard from KDDI Phone contains garbage lines
// between 'END:VCARD' and next 'BEGIN:VCARD'.
if (!readBeginVCard(true)) {
mBuilder.close();
return false;
}
long start;
if (mBuilder != null) {
start = System.currentTimeMillis();
mBuilder.startRecord("VCARD");
mTimeReadStartRecord += System.currentTimeMillis() - start;
}
start = System.currentTimeMillis();
parseItems();
mTimeParseItems += System.currentTimeMillis() - start;
readEndVCard(true, false);
if (mBuilder != null) {
start = System.currentTimeMillis();
mBuilder.endRecord();
mTimeReadEndRecord += System.currentTimeMillis() - start;
}
return true;
}

其中不光调用了parseItems(),还调用了mBuilder.endRecord(),也就是VCardDataBuilder.endRecord(),代码如下:

     public void endRecord() {
mCurrentContactStruct.consolidateFields(); for (EntryHandler entryHandler : mEntryHandlers) {
entryHandler.onEntryCreated(mCurrentContactStruct);
}
mCurrentContactStruct.clear();
}

调用了entryHandler.onEntryCreated(mCurrentContactStruct),代码在EntryCommitter.java,如下:

     public Uri onEntryCreated(final ContactStruct contactStruct) {
long start = System.currentTimeMillis();
if (contactStruct != null) {
mRawContactUri = contactStruct.pushIntoContentResolver(mContentResolver);
}
mTimeToCommit += System.currentTimeMillis() - start;
return mRawContactUri;
}

EntryCommitter类我们在前面doActuallyReadOneVCard()方法中见过。其又调用了ontactStruct.pushIntoContentResolver(mContentResolver),这一下子又跑到ContactStruct.pushIntoContentResolver()方法,代码部分如下:

 public Uri pushIntoContentResolver(ContentResolver resolver) {
if (mBuilder == null) {
mBuilder = new ContactOperationBuilder(resolver);
}
mBuilder.openSession();
mBuilder.newInsert(RawContacts.CONTENT_URI); String myGroupsId = null;
String myGroupsRowId = null;
boolean hasValue = false; if (mAccount != null) {
mBuilder.withValue(RawContacts.ACCOUNT_NAME, mAccount.name);
mBuilder.withValue(RawContacts.ACCOUNT_TYPE, mAccount.type); // Assume that caller side creates this group if it does not exist.
// TODO: refactor this code along with the change in GoogleSource.java
if (ACCOUNT_TYPE_GOOGLE.equals(mAccount.type)) {
Cursor cursor = null;
try {
cursor = resolver.query(Groups.CONTENT_URI,
new String[] {Groups.SOURCE_ID, Groups._ID },
Groups.TITLE + "=?"
+ " and " + Groups.ACCOUNT_TYPE + "=?"
+ " and " + Groups.ACCOUNT_NAME + "=?",
new String[] {GoogleAccountType.GOOGLE_MY_CONTACTS_GROUP,
mAccount.type, mAccount.name}, null);
if (cursor != null && cursor.moveToFirst()) {
myGroupsId = cursor.getString(0);
myGroupsRowId = cursor.getString(1);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
} else {
String account = null;
mBuilder.withValue(RawContacts.ACCOUNT_NAME, account);
mBuilder.withValue(RawContacts.ACCOUNT_TYPE, account); }
mBuilder.build(null, true); // In case that one contact could be committed in different batch
// If last commit fail, mDiscardRest set true to get rid of rest of
// the contact info. if (!(TextUtils.isEmpty(mFamilyName) && TextUtils.isEmpty(mGivenName)
&& TextUtils.isEmpty(mPhoneticFamilyName) && TextUtils.isEmpty(mPhoneticGivenName) && TextUtils
.isEmpty(mFullName))) {
mBuilder.newInsert(Data.CONTENT_URI);
mBuilder.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE); mBuilder.withValue(StructuredName.GIVEN_NAME, mGivenName);
mBuilder.withValue(StructuredName.FAMILY_NAME, mFamilyName);
mBuilder.withValue(StructuredName.MIDDLE_NAME, mMiddleName);
mBuilder.withValue(StructuredName.PREFIX, mPrefix);
mBuilder.withValue(StructuredName.SUFFIX, mSuffix); mBuilder.withValue(StructuredName.PHONETIC_GIVEN_NAME, mPhoneticGivenName);
mBuilder.withValue(StructuredName.PHONETIC_FAMILY_NAME, mPhoneticFamilyName);
mBuilder.withValue(StructuredName.PHONETIC_MIDDLE_NAME, mPhoneticMiddleName); mBuilder.withValue(StructuredName.DISPLAY_NAME, getDisplayName());
mBuilder.build(StructuredName.RAW_CONTACT_ID, false);
hasValue = true;
} if (mNickNameList != null && mNickNameList.size() > 0) {
boolean first = true;
for (String nickName : mNickNameList) {
mBuilder.newInsert(Data.CONTENT_URI);
mBuilder.withValue(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE); mBuilder.withValue(Nickname.TYPE, Nickname.TYPE_DEFAULT);
mBuilder.withValue(Nickname.NAME, nickName);
if (first) {
mBuilder.withValue(Data.IS_PRIMARY, 1);
first = false;
}
mBuilder.build(Nickname.RAW_CONTACT_ID, false);
hasValue = true;
}
}
......

看到了吧,在组装ContactOperationBuilder,这是要保存联系人到数据库的节奏啊,果然,继续看mBuilder.build(***)方法,如下:

 public void build(String key, boolean openAccount) {
if (mDiscardRest) {
return;
}
if (mWrapBuilder == null) {
return;
} // if current operation oversize abandon it
if (mCurrentOperationSizeInByte >= MAX_OPERATION_SIZE) {
mDiscardRest = true;
mCurrentOperationSizeInByte = 0;
return;
} avoidOperationOverFlow(); if (key != null) {
withValueBackReference(key);
} ContentProviderOperation operation = mWrapBuilder.build();
if (!openAccount) {
mValidDataCommit = true;
mOperationList.add(operation);
}
if (mOperationList.size() >= COMMIT_GATE) {
Uri uri = apply(); (1) if (uri != null) {
mRawContactId = ContentUris.parseId(uri);
} }
if (openAccount) {
mOperationList.add(operation);
} mOperationSizeInByte += mCurrentOperationSizeInByte;
mCurrentOperationSizeInByte = 0;
} public Uri apply() {
ContentProviderResult[] cpr = null;
try {
if (mOperationList != null && mOperationList.size() > 0) {
cpr = mResolver.applyBatch(ContactsContract.AUTHORITY, mOperationList); (2)
for (ContentProviderOperation cpo : mOperationList) {
Log.d("D3", "cpo.toString = " + cpo.toString());
}
} } if (mOperationList != null) {
mOperationList.clear();
}
mOperationListSizeAtOpenSession = 0; Uri uri = null;
// if cpr.length > mCurrentContactRecord means last
// applyBatch commit whole contacts and parts.
if (cpr != null) {
if (cpr.length > mCurrentContactRecord) {
uri = cpr[mCurrentContactRecord].uri;
mContactAppendum = true;
} else if (cpr.length == mCurrentContactRecord) {
// return first contact uri in last apply
uri = cpr[0].uri;
}
}
mCurrentContactRecord = 0; return uri;
}

在build()方法(1)代码处,满足条件后会调用apply()方法,看apply()中(2)的方法,保存了吧。

呵呵,Phonebook导入.vcf的过程分析至此结束,至于是如何解码中文姓名和头像的,会专门写文章研究这个问题的,因为要解码肯定得先编码,是不?怎还得先搞清楚到底是如何编码的,才能弄明白要如何解码。

05-07 15:29