概述
手機和 wifi 已經改變了人們的生活方式,成為生活的必需品。手機號碼和寬帶賬號成為運營商相互競爭的重要一環,雙卡雙待的手機需求也逐漸增大,大多數手機廠商將主打手機改為雙卡雙待全網通,而運營商在占領主SIM卡后,對SIM卡2的欲望越來越大,獲取SIM卡2的信息的需求也變大,只有知己知彼,才能占得先機。
這里簡單介紹一下 Android 手機如何讀取 Sim 卡信息
關鍵類
必要權限:
{@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
一、 一個重要的表
- siminfo telephony.db 中記錄Sim卡信息的表,可以從建表的 sql 語句中讀取該表的信息
CREATE TABLE siminfo(
_id INTEGER PRIMARY KEY AUTOINCREMENT, //主鍵ID,為使用中的subId
icc_id TEXT NOT NULL, //卡槽ID
sim_id INTEGER DEFAULT -1, //SIM_ID 卡槽ID:
-1 - 沒插入、 0 - 卡槽1 、1 - 卡槽2
display_name TEXT, //顯示名
carrier_name TEXT, //運行商
name_source INTEGER DEFAULT 0, //顯示名的來源,0 - 系統分配 1 - 用戶修改
color INTEGER DEFAULT 0, //顯示顏色,沒什么用
number TEXT, //電話號碼
display_number_format INTEGER NOT NULL DEFAULT 1, //
data_roaming INTEGER DEFAULT 0, //是否支持漫游
mcc INTEGER DEFAULT 0, //移動國家碼
mnc INTEGER DEFAULT 0 //移動網絡碼
);
可以通過 ContentProvider 進行查詢
public void testReadNameByPhone() {
Uri uri = Uri.parse("content://telephony/siminfo"); //訪問raw_contacts表
ContentResolver resolver = getApplicationContext().getContentResolver();
Cursor cursor = resolver.query(uri, new String[]{"_id","icc_id", "sim_id","display_name","carrier_name","name_source","color","number","display_number_format","data_roaming","mcc","mnc"}, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
LogUtils.e(cursor.getString(cursor.getColumnIndex("_id")));
LogUtils.e(cursor.getString(cursor.getColumnIndex("sim_id")));
LogUtils.e(cursor.getString(cursor.getColumnIndex("carrier_name")));
LogUtils.e(cursor.getString(cursor.getColumnIndex("display_name")));
LogUtils.e(cursor.getString(cursor.getColumnIndex("number")));
}
cursor.close();
}
}
二、 二個重要的類
- SubscriptionManager 讀取 siminfo 數據庫的信息管理類,僅支持5.1版本以上
- TelephonyManager 手機SIM信息管理類
三、 三個重要id
slotId 卡槽ID 雙卡的基本就是0,1
phoneId 電話ID 與 slotId 基本相同,雙卡基本都是0,1,不過在源碼 getDeviceId 方法中有個FIXME注釋
// FIXME this assumes phoneId == slotId
因此Android源碼也只是假設 phoneId == slotId,可能會在以后修改 phoneIdsubId 在 TelephonyManager 類中最常用的ID,但也是最不固定的ID,隨著使用手機號碼的增加,這個值遞增,其實本質就是siminfo的_id
讀取信息方法
一、 版本超過5.1(API 22)
使用 SubscriptionManager 類進行讀取信息
SubscriptionManager mSubscriptionManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
mSubscriptionManager.getActiveSubscriptionInfoCountMax();//手機SIM卡數
mSubscriptionManager.getActiveSubscriptionInfoCount();//手機使用的SIM卡數
List<SubscriptionInfo> activeSubscriptionInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();//手機SIM卡信息
通過 SubscriptionInfo 的實例進行讀取信息,對應的是 Siminfo 的表字段,下面為該類源碼:
package android.telephony;
public class SubscriptionInfo implements Parcelable {
/**
* Size of text to render on the icon.
*/
private static final int TEXT_SIZE = 16;
/**
* Subscription Identifier, this is a device unique number
* and not an index into an array
*/
private int mId;
/**
* The GID for a SIM that maybe associated with this subscription, empty if unknown
*/
private String mIccId;
/**
* The index of the slot that currently contains the subscription
* and not necessarily unique and maybe INVALID_SLOT_ID if unknown
*/
private int mSimSlotIndex;
/**
* The name displayed to the user that identifies this subscription
*/
private CharSequence mDisplayName;
/**
* String that identifies SPN/PLMN
* TODO : Add a new field that identifies only SPN for a sim
*/
private CharSequence mCarrierName;
/**
* The source of the name, NAME_SOURCE_UNDEFINED, NAME_SOURCE_DEFAULT_SOURCE,
* NAME_SOURCE_SIM_SOURCE or NAME_SOURCE_USER_INPUT.
*/
private int mNameSource;
/**
* The color to be used for tinting the icon when displaying to the user
*/
private int mIconTint;
/**
* A number presented to the user identify this subscription
*/
private String mNumber;
/**
* Data roaming state, DATA_RAOMING_ENABLE, DATA_RAOMING_DISABLE
*/
private int mDataRoaming;
/**
* SIM Icon bitmap
*/
private Bitmap mIconBitmap;
/**
* Mobile Country Code
*/
private int mMcc;
/**
* Mobile Network Code
*/
private int mMnc;
/**
* ISO Country code for the subscription's provider
*/
private String mCountryIso;
}
該類沒有常用的手機IMEI值和IMSI值,這個值可以通過 TelephonyManager 進行讀取,不過需要通過反射,具體可見下方關于 TelephonyManager 的介紹
telephonyManager.getDeviceId(subscriptionInfo.getSimSlotIndex());//通過slotID讀取IMEI值,版本必須高于6.0(API 23)
telephonyManager.getSubscriberId(subscriptionInfo.getSubscriptionId()) {;//通過subId讀取IMSI值,版本必須高于6.0(API 23)
二、版本低于5.1版本
使用 TelephonyManager 讀取SIM卡信息:
TelephonyManager 僅能讀取默認卡的信息,幾乎所有的通過ID讀取副卡信息的接口都添加了@hide 注釋,無法使用,因此只能通過反射的機制進行調取
2.1 TelephonyManager 讀取主卡信息
TelephonyManager telephonyManager = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE));
telephonyManager.getSimOperatorName(); //運營商信息
telephonyManager.getNetworkOperatorName(); //網絡顯示名
telephonyManager.getLine1Number(); //電話號碼
telephonyManager.getDeviceId(); //IMEI值
telephonyManager.getSubscriberId(); //IMSI值
2.2 通過反射讀取副卡信息
讀取副卡信息大多只需要1個參數,slotId 或者 subId,源碼方法如下(我們主要關心的是IMEI和IMSI,主要看getDeviceId和getSubscriberId方法):
package android.telephony;
public class TelephonyManager {
/**
* Returns the unique device ID of a subscription, for example, the IMEI for
* GSM and the MEID for CDMA phones. Return null if device ID is not available.
*
* <p>Requires Permission:
* {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
*
* @param slotId of which deviceID is returned
*/
public String getDeviceId(int slotId) {
// FIXME this assumes phoneId == slotId
try {
IPhoneSubInfo info = getSubscriberInfo();
if (info == null)
return null;
return info.getDeviceIdForPhone(slotId, mContext.getOpPackageName());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
return null;
}
}
/**
* Returns the unique subscriber ID, for example, the IMSI for a GSM phone
* for a subscription.
* Return null if it is unavailable.
* <p>
* Requires Permission:
* {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
*
* @param subId whose subscriber id is returned
* @hide
*/
public String getSubscriberId(int subId) {
try {
IPhoneSubInfo info = getSubscriberInfo();
if (info == null)
return null;
return info.getSubscriberIdForSubscriber(subId, mContext.getOpPackageName());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
// This could happen before phone restarts due to crashing
return null;
}
}
/**
* Returns the Service Provider Name (SPN).
*
* @hide
*/
public String getSimOperatorNameForPhone(int phoneId) {
return getTelephonyProperty(phoneId,
TelephonyProperties.PROPERTY_ICC_OPERATOR_ALPHA, "");
}
/**
* Returns the numeric name (MCC+MNC) of current registered operator
* for a particular subscription.
* <p>
* Availability: Only when user is registered to a network. Result may be
* unreliable on CDMA networks (use {@link #getPhoneType()} to determine if
* on a CDMA network).
*
* @param phoneId
* @hide
**/
public String getNetworkOperatorForPhone(int phoneId) {
return getTelephonyProperty(phoneId, TelephonyProperties.PROPERTY_OPERATOR_NUMERIC, "");
}
/**
* Returns the phone number string for line 1, for example, the MSISDN
* for a GSM phone for a particular subscription. Return null if it is unavailable.
* <p>
* Requires Permission:
* {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
* OR
* {@link android.Manifest.permission#READ_SMS}
* <p>
* The default SMS app can also use this.
*
* @param subId whose phone number for line 1 is returned
* @hide
*/
public String getLine1Number(int subId) {
String number = null;
try {
ITelephony telephony = getITelephony();
if (telephony != null)
number = telephony.getLine1NumberForDisplay(subId, mContext.getOpPackageName());
} catch (RemoteException ex) {
} catch (NullPointerException ex) {
}
if (number != null) {
return number;
}
try {
IPhoneSubInfo info = getSubscriberInfo();
if (info == null)
return null;
return info.getLine1NumberForSubscriber(subId, mContext.getOpPackageName());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
// This could happen before phone restarts due to crashing
return null;
}
}
/**
* Returns the serial number for the given subscription, if applicable. Return null if it is
* unavailable.
* <p>
* @param subId for which Sim Serial number is returned
* Requires Permission:
* {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
* @hide
*/
public String getSimSerialNumber(int subId) {
try {
IPhoneSubInfo info = getSubscriberInfo();
if (info == null)
return null;
return info.getIccSerialNumberForSubscriber(subId, mContext.getOpPackageName());
} catch (RemoteException ex) {
return null;
} catch (NullPointerException ex) {
// This could happen before phone restarts due to crashing
return null;
}
}
}
可以看到源碼中的這些方法均加了 @hide 的參數,無法直接調用,這里就需要用到反射:
/**
* 通過反射調取@hide的方法
*
* @param predictedMethodName 方法名
* @param id 參數
* @return 返回方法調用的結果
* @throws MethodNotFoundException 方法沒有找到
*/
private static String getReflexMethodWithId(String predictedMethodName, String id) throws MethodNotFoundException {
String result = null;
TelephonyManager telephony = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
try {
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);
Class<?>[] parameterTypes = getSimID.getParameterTypes();
Object[] obParameter = new Object[parameterTypes.length];
if (parameterTypes[0].getSimpleName().equals("int")) {
obParameter[0] = Integer.valueOf(id);
} else {
obParameter[0] = id;
}
Object ob_phone = getSimID.invoke(telephony, obParameter);
if (ob_phone != null) {
result = ob_phone.toString();
}
} catch (Exception e) {
LogUtils.d(e.fillInStackTrace());
throw new MethodNotFoundException(predictedMethodName);
}
return result;
}
/**
* 通過反射調取@hide的方法
*
* @param predictedMethodName 方法名
* @return 返回方法調用的結果
* @throws MethodNotFoundException 方法沒有找到
*/
private static String getReflexMethod(String predictedMethodName) throws MethodNotFoundException {
String result = null;
TelephonyManager telephony = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
try {
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Method getSimID = telephonyClass.getMethod(predictedMethodName);
Object ob_phone = getSimID.invoke(telephony);
if (ob_phone != null) {
result = ob_phone.toString();
}
} catch (Exception e) {
LogUtils.d(e.fillInStackTrace());
throw new MethodNotFoundException(predictedMethodName);
}
return result;
}
現在就可以通過反射進行調用方法讀取數據了
//IMEI,通過slotId,比較準確
getReflexMethodWithId("getDeviceId",“1”);
//IMSI,通過subId,很不準確,保障準確率有兩種方式
//1. 通過 SubscriptionInfo.getSubscriptionId() 獲得準確的 subId 進行調用
//2. 從0開始遍歷20次或更多次,找到不等于主卡IMSI的值
getReflexMethodWithId("getSubscriberId",“1”);
//運營商信息,PhoneId,基本準確
getReflexMethodWithId(this, "getSimOperatorNameForPhone", “1”)
//subId,很不準確
getReflexMethodWithId(this, "getSimCountryIso",“1”);
//電話號碼,subid,很不準確
getReflexMethodWithId(this, "getLine1Number", “1”);
特別注意:
電話號碼和IMSI值都是用過 subId 進行讀取的,這個值很不穩定,不一定就是1或者2,還有可能是3、4、5、6,不一定能讀取出來,不過在5.1版本以上可以通過 subscriptionInfo.getSubscriptionId() 獲得 subId,可以獲得確定的IMEI值和IMSI值
根據 Android 版本的不同,有些方法不一定能反射得到,目前測試4.4沒有問題
總結出來一個幫助類 PhoneUtils:
public class PhoneUtils {
/**
* 構造類
*/
private PhoneUtils() {
throw new UnsupportedOperationException("u can't instantiate me...");
}
/**
* 判斷設備是否是手機
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isPhone() {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null && tm.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE;
}
/**
* 獲取IMEI碼
* <p>需添加權限 {@code <uses-permission android:name="android.permission.READ_PHONE_STATE"/>}</p>
*
* @return IMEI碼
*/
@SuppressLint("HardwareIds")
public static String getIMEI() {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
try {
return tm != null ? tm.getDeviceId() : null;
} catch (Exception ignored) {
}
return getUniquePsuedoID();
}
/**
* 通過讀取設備的ROM版本號、廠商名、CPU型號和其他硬件信息來組合出一串15位的號碼
* 其中“Build.SERIAL”這個屬性來保證ID的獨一無二,當API < 9 無法讀取時,使用AndroidId
*
* @return 偽唯一ID
*/
public static String getUniquePsuedoID() {
String m_szDevIDShort = "35" +
Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +
Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +
Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +
Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +
Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +
Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +
Build.USER.length() % 10;
String serial;
try {
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
} catch (Exception e) {
//獲取失敗,使用AndroidId
serial = DeviceUtils.getAndroidID();
if (TextUtils.isEmpty(serial)) {
serial = "serial";
}
}
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
/**
* 獲取IMSI碼
* <p>需添加權限 {@code <uses-permission android:name="android.permission.READ_PHONE_STATE"/>}</p>
*
* @return IMSI碼
*/
@SuppressLint("HardwareIds")
public static String getIMSI() {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
try {
return tm != null ? tm.getSubscriberId() : null;
} catch (Exception ignored) {
}
return null;
}
/**
* 判斷sim卡是否準備好
*
* @return {@code true}: 是<br>{@code false}: 否
*/
public static boolean isSimCardReady() {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null && tm.getSimState() == TelephonyManager.SIM_STATE_READY;
}
/**
* 獲取Sim卡運營商名稱
* <p>中國移動、如中國聯通、中國電信</p>
*
* @return sim卡運營商名稱
*/
public static String getSimOperatorName() {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null ? tm.getSimOperatorName() : null;
}
/**
* 獲取Sim卡運營商名稱
* <p>中國移動、如中國聯通、中國電信</p>
*
* @return 移動網絡運營商名稱
*/
public static String getSimOperatorByMnc() {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
String operator = tm != null ? tm.getSimOperator() : null;
if (operator == null) {
return null;
}
switch (operator) {
case "46000":
case "46002":
case "46007":
return "中國移動";
case "46001":
return "中國聯通";
case "46003":
return "中國電信";
default:
return operator;
}
}
/**
* 獲取Sim卡序列號
* <p>
* Requires Permission:
* {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
*
* @return 序列號
*/
public static String getSimSerialNumber() {
try {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
String serialNumber = tm != null ? tm.getSimSerialNumber() : null;
return serialNumber != null ? serialNumber : "";
} catch (Exception e) {
}
return "";
}
/**
* 獲取Sim卡的國家代碼
*
* @return 國家代碼
*/
public static String getSimCountryIso() {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
return tm != null ? tm.getSimCountryIso() : null;
}
/**
* 讀取電話號碼
* <p>
* Requires Permission:
* {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
* OR
* {@link android.Manifest.permission#READ_SMS}
* <p>
*
* @return 電話號碼
*/
public static String getPhoneNumber() {
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
try {
return tm != null ? tm.getLine1Number() : null;
} catch (Exception ignored) {
}
return null;
}
/**
* 獲得卡槽數,默認為1
*
* @return 返回卡槽數
*/
public static int getSimCount() {
int count = 1;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
try {
SubscriptionManager mSubscriptionManager = (SubscriptionManager) Utils.getContext().getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
if (mSubscriptionManager != null) {
count = mSubscriptionManager.getActiveSubscriptionInfoCountMax();
return count;
}
} catch (Exception ignored) {
}
}
try {
count = Integer.parseInt(getReflexMethod("getPhoneCount"));
} catch (MethodNotFoundException ignored) {
}
return count;
}
/**
* 獲取Sim卡使用的數量
*
* @return 0, 1, 2
*/
public static int getSimUsedCount() {
int count = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
try {
SubscriptionManager mSubscriptionManager = (SubscriptionManager) Utils.getContext().getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
count = mSubscriptionManager.getActiveSubscriptionInfoCount();
return count;
} catch (Exception ignored) {
}
}
TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
count = 1;
}
try {
if (Integer.parseInt(getReflexMethodWithId("getSimState", "1")) == TelephonyManager.SIM_STATE_READY) {
count = 2;
}
} catch (MethodNotFoundException ignored) {
}
return count;
}
/**
* 獲取多卡信息
*
* @return 多Sim卡的具體信息
*/
public static List<SimInfo> getSimMultiInfo() {
List<SimInfo> infos = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
//1.版本超過5.1,調用系統方法
SubscriptionManager mSubscriptionManager = (SubscriptionManager) Utils.getContext().getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
List<SubscriptionInfo> activeSubscriptionInfoList = null;
if (mSubscriptionManager != null) {
try {
activeSubscriptionInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
} catch (Exception ignored) {
}
}
if (activeSubscriptionInfoList != null && activeSubscriptionInfoList.size() > 0) {
//1.1.1 有使用的卡,就遍歷所有卡
for (SubscriptionInfo subscriptionInfo : activeSubscriptionInfoList) {
SimInfo simInfo = new SimInfo();
simInfo.mCarrierName = subscriptionInfo.getCarrierName();
simInfo.mIccId = subscriptionInfo.getIccId();
simInfo.mSimSlotIndex = subscriptionInfo.getSimSlotIndex();
simInfo.mNumber = subscriptionInfo.getNumber();
simInfo.mCountryIso = subscriptionInfo.getCountryIso();
try {
simInfo.mImei = getReflexMethodWithId("getDeviceId", String.valueOf(simInfo.mSimSlotIndex));
simInfo.mImsi = getReflexMethodWithId("getSubscriberId", String.valueOf(subscriptionInfo.getSubscriptionId()));
} catch (MethodNotFoundException ignored) {
}
infos.add(simInfo);
}
}
}
//2.版本低于5.1的系統,首先調用數據庫,看能不能訪問到
Uri uri = Uri.parse("content://telephony/siminfo"); //訪問raw_contacts表
ContentResolver resolver = Utils.getContext().getContentResolver();
Cursor cursor = resolver.query(uri, new String[]{"_id", "icc_id", "sim_id", "display_name", "carrier_name", "name_source", "color", "number", "display_number_format", "data_roaming", "mcc", "mnc"}, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
SimInfo simInfo = new SimInfo();
simInfo.mCarrierName = cursor.getString(cursor.getColumnIndex("carrier_name"));
simInfo.mIccId = cursor.getString(cursor.getColumnIndex("icc_id"));
simInfo.mSimSlotIndex = cursor.getInt(cursor.getColumnIndex("sim_id"));
simInfo.mNumber = cursor.getString(cursor.getColumnIndex("number"));
simInfo.mCountryIso = cursor.getString(cursor.getColumnIndex("mcc"));
String id = cursor.getString(cursor.getColumnIndex("_id"));
try {
simInfo.mImei = getReflexMethodWithId("getDeviceId", String.valueOf(simInfo.mSimSlotIndex));
simInfo.mImsi = getReflexMethodWithId("getSubscriberId", String.valueOf(id));
} catch (MethodNotFoundException ignored) {
}
infos.add(simInfo);
}
cursor.close();
}
//3.通過反射讀取卡槽信息,最后通過IMEI去重
for (int i = 0; i < getSimCount(); i++) {
infos.add(getReflexSimInfo(i));
}
List<SimInfo> simInfos = ConvertUtils.removeDuplicateWithOrder(infos);
if (simInfos.size() < getSimCount()) {
for (int i = simInfos.size(); i < getSimCount(); i++) {
simInfos.add(new SimInfo());
}
}
return simInfos;
}
@Nullable
public static String getSecondIMSI() {
int maxCount = 20;
if (TextUtils.isEmpty(getIMSI())) {
return null;
}
for (int i = 0; i < maxCount; i++) {
String imsi = null;
try {
imsi = getReflexMethodWithId("getSubscriberId", String.valueOf(i));
} catch (MethodNotFoundException ignored) {
LogUtils.d(ignored);
}
if (!TextUtils.isEmpty(imsi) && !imsi.equals(getIMSI())) {
return imsi;
}
}
return null;
}
/**
* 通過反射獲得SimInfo的信息
* 當index為0時,讀取默認信息
*
* @param index 位置,用來當subId和phoneId
* @return {@link SimInfo} sim信息
*/
@NonNull
private static SimInfo getReflexSimInfo(int index) {
SimInfo simInfo = new SimInfo();
simInfo.mSimSlotIndex = index;
try {
simInfo.mImei = getReflexMethodWithId("getDeviceId", String.valueOf(simInfo.mSimSlotIndex));
//slotId,比較準確
simInfo.mImsi = getReflexMethodWithId("getSubscriberId", String.valueOf(simInfo.mSimSlotIndex));
//subId,很不準確
simInfo.mCarrierName = getReflexMethodWithId("getSimOperatorNameForPhone", String.valueOf(simInfo.mSimSlotIndex));
//PhoneId,基本準確
simInfo.mCountryIso = getReflexMethodWithId("getSimCountryIso", String.valueOf(simInfo.mSimSlotIndex));
//subId,很不準確
simInfo.mIccId = getReflexMethodWithId("getSimSerialNumber", String.valueOf(simInfo.mSimSlotIndex));
//subId,很不準確
simInfo.mNumber = getReflexMethodWithId("getLine1Number", String.valueOf(simInfo.mSimSlotIndex));
//subId,很不準確
} catch (MethodNotFoundException ignored) {
}
return simInfo;
}
/**
* 通過反射調取@hide的方法
*
* @param predictedMethodName 方法名
* @return 返回方法調用的結果
* @throws MethodNotFoundException 方法沒有找到
*/
private static String getReflexMethod(String predictedMethodName) throws MethodNotFoundException {
String result = null;
TelephonyManager telephony = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
try {
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Method getSimID = telephonyClass.getMethod(predictedMethodName);
Object ob_phone = getSimID.invoke(telephony);
if (ob_phone != null) {
result = ob_phone.toString();
}
} catch (Exception e) {
LogUtils.d(e.fillInStackTrace());
throw new MethodNotFoundException(predictedMethodName);
}
return result;
}
/**
* 通過反射調取@hide的方法
*
* @param predictedMethodName 方法名
* @param id 參數
* @return 返回方法調用的結果
* @throws MethodNotFoundException 方法沒有找到
*/
private static String getReflexMethodWithId(String predictedMethodName, String id) throws MethodNotFoundException {
String result = null;
TelephonyManager telephony = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
try {
Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
Class<?>[] parameter = new Class[1];
parameter[0] = int.class;
Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);
Class<?>[] parameterTypes = getSimID.getParameterTypes();
Object[] obParameter = new Object[parameterTypes.length];
if (parameterTypes[0].getSimpleName().equals("int")) {
obParameter[0] = Integer.valueOf(id);
} else if (parameterTypes[0].getSimpleName().equals("long")) {
obParameter[0] = Long.valueOf(id);
} else {
obParameter[0] = id;
}
Object ob_phone = getSimID.invoke(telephony, obParameter);
if (ob_phone != null) {
result = ob_phone.toString();
}
} catch (Exception e) {
LogUtils.d(e.fillInStackTrace());
throw new MethodNotFoundException(predictedMethodName);
}
return result;
}
/**
* SIM 卡信息
*/
public static class SimInfo {
/** 運營商信息:中國移動 中國聯通 中國電信 */
public CharSequence mCarrierName;
/** 卡槽ID,SimSerialNumber */
public CharSequence mIccId;
/** 卡槽id, -1 - 沒插入、 0 - 卡槽1 、1 - 卡槽2 */
public int mSimSlotIndex;
/** 號碼 */
public CharSequence mNumber;
/** 城市 */
public CharSequence mCountryIso;
/** 設備唯一識別碼 */
public CharSequence mImei = getIMEI();
/** SIM的編號 */
public CharSequence mImsi;
/**
* 通過 IMEI 判斷是否相等
*
* @param obj
* @return
*/
@Override
public boolean equals(Object obj) {
return obj != null && obj instanceof SimInfo && (TextUtils.isEmpty(((SimInfo) obj).mImei) || ((SimInfo) obj).mImei.equals(mImei));
}
@Override
public String toString() {
return "SimInfo{" +
"mCarrierName=" + mCarrierName +
", mIccId=" + mIccId +
", mSimSlotIndex=" + mSimSlotIndex +
", mNumber=" + mNumber +
", mCountryIso=" + mCountryIso +
", mImei=" + mImei +
", mImsi=" + mImsi +
'}';
}
}
/**
* 反射未找到方法
*/
private static class MethodNotFoundException extends Exception {
public static final long serialVersionUID = -3241033488141442594L;
MethodNotFoundException(String info) {
super(info);
}
}
}