Android: 獲取短信的發信人

既[url=http://kevinlynx.iteye.com/blog/843281]上次的測試[/url],通過取得短信裏的person字段,然後通過person字段從聯繫人表裏取出聯繫人信息,總是存在問題:
1、如果短信是在建立聯繫人信息之前收到的,person字段依然是0;
2、在我的真機上即使person不爲0,Cursor::moveToFirst依然失敗,導致獲取不出聯繫人信息。

今天無意看到分代碼[url=http://code.google.com/p/android-sms]SMS Backup[/url],看到裏面獲取聯繫人信息的代碼:
[code]
private PersonRecord lookupPerson(String address) {
if (!mPeopleCache.containsKey(address)) {
// Look phone number
Uri personUri = Uri.withAppendedPath(Phones.CONTENT_FILTER_URL, address);
Cursor phoneCursor = mContext.getContentResolver().query(personUri, PHONE_PROJECTION,
null, null, null);
if (phoneCursor.moveToFirst()) {
int indexPersonId = phoneCursor.getColumnIndex(Phones.PERSON_ID);
int indexName = phoneCursor.getColumnIndex(People.NAME);
int indexNumber = phoneCursor.getColumnIndex(Phones.NUMBER);
long personId = phoneCursor.getLong(indexPersonId);
String name = phoneCursor.getString(indexName);
String number = phoneCursor.getString(indexNumber);
phoneCursor.close();

[/code]

大概就是說android api裏提供了相對簡單的查詢方式:
[code]
Uri personUri = Uri.withAppendedPath(Phones.CONTENT_FILTER_URL, address);
Cursor phoneCursor = mContext.getContentResolver().query(personUri, PHONE_PROJECTION,
null, null, null);
[/code]
之前我也考慮過通過號碼從聯繫人表裏遍歷出聯繫人信息,但是,這就需要自己去處理電話號碼的不同表示,例如:
+86134xxxxxxxx
甚至是飛信的轉發號碼:12520134xxxxxxxx。

上面列的代碼中,Uri大概就可以處理自動處理以上情況。不過,上面的代碼已經被google標記爲deprecated,查了下文檔和網絡資料,我寫了如下的函數:
[code]
ContactItem getContactByAddr(Context context, final SMSItem sms) {
Uri personUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI, sms.mAddress);
Cursor cur = context.getContentResolver().query(personUri,
new String[] { PhoneLookup.DISPLAY_NAME },
null, null, null );
if( cur.moveToFirst() ) {
int nameIdx = cur.getColumnIndex(PhoneLookup.DISPLAY_NAME);
ContactItem item = new ContactItem();
item.mName = cur.getString(nameIdx);
cur.close();
return item;
}
return null;
}
[/code]
以上代碼就可以通過電話號碼取得聯繫人信息,在我的真機上也可以正確處理+86134xxxxxxxx/12520134xxxxxxxx之類的號碼。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章