从SIM卡中获取联系人信息
Uri uri =Uri.parse("content://icc/adn");
String[] projection = {"_id","name", "number"};
Cursor cursor = managedQuery(uri,projection, null, null, "name");
if(cursor!=null){
while(cursor.moveToNext()){
Stringname = cursor.getString(cursor.getColumnIndex("name"));
Stringphone = cursor.getString(cursor.getColumnIndex("number"));
}
}
在文件AndroidManifest.xml中添加权限
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Android系统内部通过Contentprovider对外共享Sim卡存放的联系人等信息,你可以通过操作Contentprovider来实现Sim卡信息的添删改查操作。 内部实现源代码参见备注栏:
package com.android.internal.telephony;
import android.content.ContentProvider;
import android.content.UriMatcher;
import android.content.ContentValues;
import com.android.internal.database.ArrayListCursor;
import android.database.Cursor;
import android.net.Uri;
import android.os.SystemProperties;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.text.TextUtils;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
importcom.android.internal.telephony.IccConstants;
importcom.android.internal.telephony.AdnRecord;
importcom.android.internal.telephony.IIccPhoneBook;
public class IccProvider extendsContentProvider {
private static final String TAG = "IccProvider";
private static final boolean DBG = false;
private static final String[] ADDRESS_BOOK_COLUMN_NAMES = new String[] {
"name",
"number"
};
private static final int ADN = 1;
private static final int FDN = 2;
private static final int SDN = 3;
private static final String STR_TAG = "tag";
private static final String STR_NUMBER = "number";
private static final String STR_PIN2 = "pin2";
private static final UriMatcher URL_MATCHER = newUriMatcher(UriMatcher.NO_MATCH);
static {
URL_MATCHER.addURI("icc", "adn", ADN);
URL_MATCHER.addURI("icc", "fdn", FDN);
URL_MATCHER.addURI("icc", "sdn", SDN);
}
private boolean mSimulator;
@Override
public boolean onCreate() {
String device = SystemProperties.get("ro.product.device");
if (!TextUtils.isEmpty(device)) {
mSimulator = false;
} else {
// simulator
mSimulator = true;
}
return true;
}
@Override
public Cursor query(Uri url, String[] projection, String selection,
String[] selectionArgs, String sort) {
ArrayList<ArrayList> results;
if (!mSimulator) {
switch (URL_MATCHER.match(url)) {
case ADN:
results =loadFromEf(IccConstants.EF_ADN);
break;
case FDN:
results =loadFromEf(IccConstants.EF_FDN);
break;
case SDN:
results =loadFromEf(IccConstants.EF_SDN);
break;
default:
throw newIllegalArgumentException("Unknown URL " + url);
}
} else {
// Fake up some data for the simulator
results = new ArrayList<ArrayList>(4);
ArrayList<String> contact;
contact = new ArrayList<String>();
contact.add("Ron Stevens/H");
contact.add("512-555-5038");
results.add(contact);
contact = new ArrayList<String>();
contact.add("Ron Stevens/M");
contact.add("512-555-8305");
results.add(contact);
contact = new ArrayList<String>();
contact.add("MelissaOwens");
contact.add("512-555-8305");
results.add(contact);
contact = new ArrayList<String>();
contact.add("Directory Assistence");
contact.add("411");
results.add(contact);
}
return new ArrayListCursor(ADDRESS_BOOK_COLUMN_NAMES, results);
}
@Override
public String getType(Uri url) {
switch (URL_MATCHER.match(url)) {
case ADN:
case FDN:
case SDN:
return"vnd.android.cursor.dir/sim-contact";
default:
throw newIllegalArgumentException("Unknown URL " + url);
}
}
@Override
public Uri insert(Uri url, ContentValues initialValues) {
Uri resultUri;
int efType;
String pin2 = null;
if (DBG) log("insert");
int match = URL_MATCHER.match(url);
switch (match) {
case ADN:
efType = IccConstants.EF_ADN;
break;
case FDN:
efType = IccConstants.EF_FDN;
pin2 =initialValues.getAsString("pin2");
break;
default:
throw newUnsupportedOperationException(
"Cannot insertinto URL: " + url);
}
String tag = initialValues.getAsString("tag");
String number = initialValues.getAsString("number");
boolean success = addIccRecordToEf(efType, tag, number, pin2);
if (!success) {
return null;
}
StringBuilder buf = new StringBuilder("content://im/");
switch (match) {
case ADN:
buf.append("adn/");
break;
case FDN:
buf.append("fdn/");
break;
}
// TODO: we need to find out the rowId for the newly added record
buf.append(0);
resultUri = Uri.parse(buf.toString());
/*
// notify interested parties that an insertion happened
getContext().getContentResolver().notifyInsert(
resultUri, rowID, null);
*/
return resultUri;
}
private String normalizeValue(String inVal) {
int len = inVal.length();
String retVal = inVal;
if (inVal.charAt(0) == '\'' && inVal.charAt(len-1) == '\'') {
retVal = inVal.substring(1, len-1);
}
return retVal;
}
@Override
public int delete(Uri url, String where, String[] whereArgs) {
int efType;
if (DBG) log("delete");
int match = URL_MATCHER.match(url);
switch (match) {
case ADN:
efType = IccConstants.EF_ADN;
break;
case FDN:
efType = IccConstants.EF_FDN;
break;
default:
throw newUnsupportedOperationException(
"Cannot insertinto URL: " + url);
}
// parse where clause
String tag = null;
String number = null;
String pin2 = null;
String[] tokens = where.split("AND");
int n = tokens.length;
while (--n >= 0) {
String param = tokens[n];
if (DBG) log("parsing '" + param + "'");
String[] pair = param.split("=");
if (pair.length != 2) {
Log.e(TAG, "resolve: badwhereClause parameter: " + param);
continue;
}
String key = pair[0].trim();
String val = pair[1].trim();
if (STR_TAG.equals(key)) {
tag = normalizeValue(val);
} else if (STR_NUMBER.equals(key)) {
number = normalizeValue(val);
} else if (STR_PIN2.equals(key)) {
pin2 = normalizeValue(val);
}
}
if (TextUtils.isEmpty(tag)) {
return 0;
}
if (efType == FDN && TextUtils.isEmpty(pin2)) {
return 0;
}
boolean success = deleteIccRecordFromEf(efType, tag, number, pin2);
if (!success) {
return 0;
}
return 1;
}
@Override
public int update(Uri url, ContentValues values, String where, String[]whereArgs) {
int efType;
String pin2 = null;
if (DBG) log("update");
int match = URL_MATCHER.match(url);
switch (match) {
case ADN:
efType = IccConstants.EF_ADN;
break;
case FDN:
efType = IccConstants.EF_FDN;
pin2 =values.getAsString("pin2");
break;
default:
throw newUnsupportedOperationException(
"Cannot insertinto URL: " + url);
}
String tag = values.getAsString("tag");
String number = values.getAsString("number");
String newTag = values.getAsString("newTag");
String newNumber = values.getAsString("newNumber");
boolean success = updateIccRecordInEf(efType, tag, number,
newTag, newNumber, pin2);
if (!success) {
return 0;
}
return 1;
}
private ArrayList<ArrayList> loadFromEf(int efType) {
ArrayList<ArrayList> results = new ArrayList<ArrayList>();
List<AdnRecord> adnRecords = null;
if (DBG) log("loadFromEf: efType=" + efType);
try {
IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(
ServiceManager.getService("simphonebook"));
if (iccIpb != null) {
adnRecords =iccIpb.getAdnRecordsInEf(efType);
}
} catch (RemoteException ex) {
// ignore it
} catch (SecurityException ex) {
if (DBG) log(ex.toString());
}
if (adnRecords != null) {
// Load the results
int N = adnRecords.size();
if (DBG) log("adnRecords.size=" + N);
for (int i = 0; i < N ; i++) {
loadRecord(adnRecords.get(i),results);
}
} else {
// No results to load
Log.w(TAG, "Cannot load ADN records");
results.clear();
}
if (DBG) log("loadFromEf: return results");
return results;
}
private boolean
addIccRecordToEf(int efType, String name, String number, String pin2) {
if (DBG) log("addIccRecordToEf: efType=" + efType + ",name=" + name +
", number=" +number);
boolean success = false;
// TODO: do we need to call getAdnRecordsInEf() before calling
// updateAdnRecordsInEfBySearch()? In any case, we will leave
// the UI level logic to fill that prereq if necessary. But
// hopefully, we can remove this requirement.
try {
IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(
ServiceManager.getService("simphonebook"));
if (iccIpb != null) {
success =iccIpb.updateAdnRecordsInEfBySearch(efType, "", "",
name, number, pin2);
}
} catch (RemoteException ex) {
// ignore it
} catch (SecurityException ex) {
if (DBG) log(ex.toString());
}
if (DBG) log("addIccRecordToEf: " + success);
return success;
}
private boolean
updateIccRecordInEf(int efType, String oldName, String oldNumber,
String newName, String newNumber,String pin2) {
if (DBG) log("updateIccRecordInEf: efType=" + efType +
", oldname=" +oldName + ", oldnumber=" + oldNumber +
", newname=" +newName + ", newnumber=" + newNumber);
boolean success = false;
try {
IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(
ServiceManager.getService("simphonebook"));
if (iccIpb != null) {
success =iccIpb.updateAdnRecordsInEfBySearch(efType,
oldName, oldNumber,newName, newNumber, pin2);
}
} catch (RemoteException ex) {
// ignore it
} catch (SecurityException ex) {
if (DBG) log(ex.toString());
}
if (DBG) log("updateIccRecordInEf: " + success);
return success;
}
private boolean deleteIccRecordFromEf(int efType, String name, Stringnumber, String pin2) {
if (DBG) log("deleteIccRecordFromEf: efType=" + efType +
", name=" + name +", number=" + number + ", pin2=" + pin2);
boolean success = false;
try {
IIccPhoneBook iccIpb = IIccPhoneBook.Stub.asInterface(
ServiceManager.getService("simphonebook"));
if (iccIpb != null) {
success =iccIpb.updateAdnRecordsInEfBySearch(efType,
name, number,"", "", pin2);
}
} catch (RemoteException ex) {
// ignore it
} catch (SecurityException ex) {
if (DBG) log(ex.toString());
}
if (DBG) log("deleteIccRecordFromEf: " + success);
return success;
}
/**
* Loads an AdnRecord into an ArrayList. Must be called with mLock held.
*
* @param record the ADN record to load from
* @param results the array list to put the results in
*/
private void loadRecord(AdnRecord record,
ArrayList<ArrayList> results) {
if (!record.isEmpty()) {
ArrayList<String> contact = new ArrayList<String>(2);
String alphaTag = record.getAlphaTag();
String number = record.getNumber();
if (DBG) log("loadRecord: " + alphaTag + ", " +number);
contact.add(alphaTag);
contact.add(number);
results.add(contact);
}
}
private void log(String msg) {
Log.d(TAG, "[IccProvider] " + msg);
}
}
2.Contacts (访问通信录中的联系人和添加联系人)
<?xml version="1.0"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.itcast.contacts"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"android:label="@string/app_name">
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:name="android.test.runner"/>
</application>
<uses-sdk android:minSdkVersion="8"/>
<instrumentation android:targetPackage="cn.itcast.contacts" android:name="android.test.InstrumentationTestRunner"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
</manifest>
public class MainActivity extends Activity {
/** Calledwhen the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
package cn.itcast.test;
import java.util.ArrayList;
importandroid.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.util.Log;
public class ContactsTest extendsAndroidTestCase {
privatestatic final String TAG = "ContactsTest";
//获取所有联系人
publicvoid testContacts() throws Exception{
Uriuri = Uri.parse("content://com.android.contacts/contacts");
ContentResolverresolver = getContext().getContentResolver();
Cursorcursor = resolver.query(uri, new String[]{"_id"}, null, null, null);
while(cursor.moveToNext()){
intcontactid = cursor.getInt(0);
StringBuildersb = new StringBuilder("contactid=");
sb.append(contactid);
uri= Uri.parse("content://com.android.contacts/contacts/"+ contactid+"/data");
Cursordatacursor = resolver.query(uri, new String[]{"mimetype","data1","data2"},null, null, null);
while(datacursor.moveToNext()){
Stringdata = datacursor.getString(datacursor.getColumnIndex("data1"));
Stringtype = datacursor.getString(datacursor.getColumnIndex("mimetype"));
if("vnd.android.cursor.item/name".equals(type)){//姓名
sb.append(",name="+data);
}elseif("vnd.android.cursor.item/email_v2".equals(type)){//email
sb.append(",email="+data);
}elseif("vnd.android.cursor.item/phone_v2".equals(type)){//phone
sb.append(",phone="+data);
}
}
Log.i(TAG,sb.toString());
}
}
//根据号码获取联系人的姓名
publicvoid testContactNameByNumber() throws Exception{
Stringnumber = "18601025011";
Uriuri = Uri.parse("content://com.android.contacts/data/phones/filter/"+number);
ContentResolver resolver =getContext().getContentResolver();
Cursorcursor = resolver.query(uri, new String[]{"display_name"}, null,null, null);
if(cursor.moveToFirst()){
Stringname = cursor.getString(0);
Log.i(TAG,name);
}
cursor.close();
}
//添加联系人
publicvoid testAddContact() throws Exception{
Uriuri = Uri.parse("content://com.android.contacts/raw_contacts");
ContentResolverresolver = getContext().getContentResolver();
ContentValuesvalues = new ContentValues();
longcontactid = ContentUris.parseId(resolver.insert(uri, values));
//添加姓名
uri= Uri.parse("content://com.android.contacts/data");
values.put("raw_contact_id",contactid);
values.put("mimetype","vnd.android.cursor.item/name");
values.put("data2","张小小");
resolver.insert(uri, values);
//添加电话
values.clear();
values.put("raw_contact_id",contactid);
values.put("mimetype","vnd.android.cursor.item/phone_v2");
values.put("data2","2");
values.put("data1","13671323507");
resolver.insert(uri,values);
//添加Email
values.clear();
values.put("raw_contact_id",contactid);
values.put("mimetype","vnd.android.cursor.item/email_v2");
values.put("data2","2");
values.put("data1","zhangxx@csdn.net");
resolver.insert(uri,values);
}
//在同一个事务中完成联系人各项数据的添加
publicvoid testAddContact2() throws Exception{
Uriuri = Uri.parse("content://com.android.contacts/raw_contacts");
ContentResolverresolver = getContext().getContentResolver();
ArrayList<ContentProviderOperation>operations = new ArrayList<ContentProviderOperation>();
ContentProviderOperationop1 = ContentProviderOperation.newInsert(uri)
.withValue("account_name",null)
.build();
operations.add(op1);
uri= Uri.parse("content://com.android.contacts/data");
ContentProviderOperationop2 = ContentProviderOperation.newInsert(uri)
.withValueBackReference("raw_contact_id",0)
.withValue("mimetype","vnd.android.cursor.item/name")
.withValue("data2","李小龙")
.build();
operations.add(op2);
ContentProviderOperationop3 = ContentProviderOperation.newInsert(uri)
.withValueBackReference("raw_contact_id",0)
.withValue("mimetype","vnd.android.cursor.item/phone_v2")
.withValue("data1","13560650505")
.withValue("data2","2")
.build();
operations.add(op3);
ContentProviderOperationop4 = ContentProviderOperation.newInsert(uri)
.withValueBackReference("raw_contact_id",0)
.withValue("mimetype","vnd.android.cursor.item/email_v2")
.withValue("data1","liming@sohu.com")
.withValue("data2","2")
.build();
operations.add(op4);
resolver.applyBatch("com.android.contacts",operations);
}
}
2397

被折叠的 条评论
为什么被折叠?



