获取系统的联系人信息
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void getContacts(View view) {
ContentResolver resolver = this.getContentResolver();
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
Cursor cursor = resolver.query(uri, null, null, null, null);
if (cursor.moveToLast()) {
String id = cursor.getString(cursor.getColumnIndex("contact_id"));
if (id != null) {
Cursor dataCursor = resolver.query(dataUri, null,
"raw_contact_id=?", new String[] { id }, null);
while (dataCursor.moveToNext()) {
String data1 = dataCursor.getString(dataCursor
.getColumnIndex("data1"));
String mimetype = dataCursor.getString(dataCursor
.getColumnIndex("mimetype"));
Toast.makeText(this, data1 + " = " + mimetype, 0).show();
}
dataCursor.close();
} else {
Toast.makeText(this, "空!", 0).show();
}
}
cursor.close();
}
}
保存联系人到系统通讯录
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void writeContact(View view) {
ContentResolver resolver = this.getContentResolver();
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
Cursor cursor = resolver.query(uri, new String[] { "_id" }, null, null,
null);
if (cursor.moveToLast()) {
int lastId = cursor.getInt(0);
int newId = lastId + 1;
ContentValues values = new ContentValues();
values.put("contact_id", newId);
resolver.insert(uri, values);
ContentValues phoneValues = new ContentValues();
phoneValues.put("data1", "13500001111");
phoneValues.put("mimetype", "vnd.android.cursor.item/phone_v2");
phoneValues.put("raw_contact_id", newId);
resolver.insert(dataUri, phoneValues);
ContentValues emaiValues = new ContentValues();
emaiValues.put("data1", "reality_jie@qq.com");
emaiValues.put("mimetype", "vnd.android.cursor.item/email_v2");
emaiValues.put("raw_contact_id", newId);
resolver.insert(dataUri, emaiValues);
ContentValues nameValues = new ContentValues();
nameValues.put("data1", "weijie");
nameValues.put("mimetype", "vnd.android.cursor.item/name");
nameValues.put("raw_contact_id", newId);
resolver.insert(dataUri, nameValues);
}
cursor.close();
Toast.makeText(this, "保存成功", 0).show();
}
}