大家都知道安卓应用在手机上比较流行,而我们使用Android如何从SIM卡中获取联系人呢?徐州北大青鸟老师做一个功能,需要同步本地联系人信息,主要从SIM卡和android通信录得到SIM卡获取联系人,由于SIM卡容量有限,它只存储了联系人的名字和号码,下面是徐州北大青鸟老师给提供的代码,有兴趣的同学可以参考一下。
private static final int NAME_COLUMN = 0;
private static final int NUMBER_COLUMN = 1;
private static final String SURI = "content://icc/adn";
private Context context = null;
private ContentResolver resolver = null;
private TelephonyManager telMgr = null;
public SimHelper(Context context)
{
this.context = context;
resolver = context.getContentResolver();
}
public TelephonyManager getTelephonyManager()
{
if (telMgr == null)
{
telMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
}
return telMgr;
}
public int getSimCardState()
{
return getTelephonyManager().getSimState();
}
public List<ContactInfo> retrieveContactInfoFromSIM()
{
List<ContactInfo> simContactInfoList = new ArrayList<ContactInfo>();
Uri uri = Uri.parse(SURI);
Cursor cursor = resolver.query(uri, null, null, null, null);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
ContactInfo contacInfo = new ContactInfo();
final NamePhoneTypePair namePhoneTypePair = new NamePhoneTypePair(
cursor.getString(NAME_COLUMN));
final String name = namePhoneTypePair.name;
final int phoneType = namePhoneTypePair.phoneType;
final String phoneNumber = cursor.getString(NUMBER_COLUMN);
setPhoneInfo(contacInfo, phoneType, phoneNumber);
contacInfo.setName(name);
simContactInfoList.add(contacInfo);
}
cursor.close();
return simContactInfoList;
}
private void setPhoneInfo(ContactInfo contactInfo, int phoneType,
String phoneNumber)
{
Phone phone = new Phone();
phone.setType(PhoneType.valueOf(phoneType));
phone.setNumber(phoneNumber);
contactInfo.getPhones().add(phone);
}
private static class NamePhoneTypePair
{
final String name;
final int phoneType;
public NamePhoneTypePair(String nameWithPhoneType)
{
// Look for /W /H /M or /O at the end of the name signifying the type
int nameLen = nameWithPhoneType.length();
if (nameLen - 2 >= 0
&& nameWithPhoneType.charAt(nameLen - 2) == '/')
{
char c = Character.toUpperCase(nameWithPhoneType.charAt(nameLen - 1));
if (c == 'W')
{
phoneType = PhoneType.Company.getPhoneType();
}
else if (c == 'M' || c == 'O')
{
phoneType = PhoneType.Mobile.getPhoneType();
}
else if (c == 'H')
{
phoneType = PhoneType.Home.getPhoneType();
}
else
{
phoneType = PhoneType.Other.getPhoneType();
}
name = nameWithPhoneType.substring(0, nameLen - 2);
}
else
{
phoneType = PhoneType.Other.getPhoneType();
name = nameWithPhoneType;
}
}
}
看到了Android apps中Phone得源码,似乎可以拿到联系人电话类型,徐州北大青鸟的技术老师可以做得到哦,有兴趣的话可以来到北大青鸟的课堂这里有很多你想不到的精彩内容!
