先在模擬器輸入三筆聯絡人的資料(包括姓名、電話號碼、電子信箱和地址)
Manifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS"/>
*****************************
main.java:
public class G_4_4_ContactsContractEmailActivity extends Activity {
/** Called when the activity is first created. */
TextView tv;
Uri uri1 = ContactsContract.Contacts.CONTENT_URI; // 聯絡人
Uri uri2 = ContactsContract.CommonDataKinds.Email.CONTENT_URI; //聯絡人的EMAIL
Uri uri3 = ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI; //聯絡人的住址
String result = "列出聯絡人的編號、名字、電子信箱和住址\n\n";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv1);
ContentResolver cr = getContentResolver();
Cursor c = cr.query(uri1, null, null, null, null);
while (c.moveToNext()) {
// 取得聯絡人ID
int contactColumnID = c.getColumnIndex(ContactsContract.Contacts._ID);
String contactID = c.getString(contactColumnID);
result += "ID: " + contactID + "\n";
//取得聯絡人的名字
int contactNameColumnIndex = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
String contactName = c.getString(contactNameColumnIndex);
result += "Name: " + contactName + "\n";
// 準備 mailCursor for email ; 所有人的ID,條件是每人的所有Email=每個人的ID號碼
Cursor mailCursor = cr.query(uri2, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?" , new String[]{contactID}, null);
// 取得Email(可能每個人有超過一個Email)
int flag = 1;
while (mailCursor.moveToNext()){
int emailColumn = mailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA1);
String emailStr = mailCursor.getString(emailColumn);
result += "信箱" + Integer.toString(flag) + ": " + emailStr + "\n";
flag++;
}
flag = 1;
mailCursor.close();
// 準備 addressCursor for Address ; 所有人的ID,條件是每人的所有address=每個人的ID號碼
Cursor addressCursor = cr.query(uri3, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[]{contactID}, null);
while (addressCursor.moveToNext()){
int addressColumn = addressCursor.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.DATA);
String addressStr = addressCursor.getString(addressColumn);
result += "住址 :" + addressStr + "\n";
}
result += "\n";
addressCursor.close();
}
c.close();
tv.setText(result);
}
}
沒有留言:
張貼留言