手機(jī)在存儲(chǔ)聯(lián)系人時(shí)支持存儲(chǔ)到手機(jī)或者sim卡碟渺,本文主要講述Android的sim卡中聯(lián)系人是如何操作的.
1、權(quán)限
由于操作聯(lián)系人的信息,所以聯(lián)系人的讀取和寫入是必不可少的哀蘑。
<uses-permission android:name="android.permission.READ_CONTACTS">
<uses-permission android:name="android.permission.WRITE_CONTACTS">
2诚卸、URI
URI的創(chuàng)建方式
Intent intent = new Intent();
intent.setData(Uri.parse("content://icc/adn/"));
uri = intent.getData();
3、查詢sim卡中的聯(lián)系人
public static void querySIMContact() {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
Log.d(TAG, "cursor count=" + cursor.getCount());
while (cursor.moveToNext()) {
String[] columnNames = cursor.getColumnNames();
for (int i = 0; i < columnNames.length; i++) {
String name = cursor.getString(0);
String number = cursor.getString(1);
String emails = cursor.getString(2);
String id = cursor.getString(3);
Log.d(TAG, "simcardinfo=" + "name=" + name + " number=" + number + " emails=" + emails + " id=" + id);
}
}
}
4绘迁、新增sim卡聯(lián)系人
public static void insertSIMContact(String name, String phoneNumber) {
ContentValues values = new ContentValues();
values.put("tag", name);
values.put("number", phoneNumber);
Uri insertInfo = context.getContentResolver().insert(uri, values);
Log.d(TAG, insertInfo.toString());
}
5合溺、刪除sim卡聯(lián)系人
public void deleteSIMContact(String name, String number) {
String where = "tag='" + name + "'";
where += " AND number='" + number + "'";
int delete = context.getContentResolver().delete(uri, where, null);
Log.d(TAG, "delete =" + delete);
}
6、更新SIM卡聯(lián)系人
public static void updateSIMContact(String oldName, String oldPhone, String newName,String newPhone) {
ContentValues values = new ContentValues();
values.put("tag", oldName);
values.put("number", oldPhone);
values.put("newTag", newName);
values.put("newNumber", newPhone);
int update = context.getContentResolver().update(uri, values, null, null);
Log.d(TAG, "update =" + update);
}
需要說(shuō)明的是缀台,刪除和更新聯(lián)系人上述方法如果運(yùn)行不生效的話棠赛,需要在where中將所有的參數(shù)屬性值都傳進(jìn)來(lái)應(yīng)該就可以了。
eg 刪除:where = "tag='" + name + " AND number='" + number + "AND emails="+""+"AND anrs="+""+"'";
關(guān)于權(quán)限需要在代碼中動(dòng)態(tài)申請(qǐng)膛腐,我在manifest中靜態(tài)申請(qǐng)的睛约,發(fā)現(xiàn)在運(yùn)行時(shí)還是會(huì)報(bào)權(quán)限的錯(cuò)誤。如果只是為了測(cè)試使用哲身,可以在設(shè)置中給自己的apk賦予聯(lián)系人的讀寫權(quán)限同樣不影響程序的運(yùn)行辩涝,當(dāng)然最好還是在代碼中對(duì)權(quán)限進(jìn)行動(dòng)態(tài)的申請(qǐng)。