Android 手機(jī)讀取SIM卡信息

概述

手機(jī)和 wifi 已經(jīng)改變了人們的生活方式纷宇,成為生活的必需品孔飒。手機(jī)號(hào)碼和寬帶賬號(hào)成為運(yùn)營(yíng)商相互競(jìng)爭(zhēng)的重要一環(huán)寄悯,雙卡雙待的手機(jī)需求也逐漸增大萤衰,大多數(shù)手機(jī)廠商將主打手機(jī)改為雙卡雙待全網(wǎng)通,而運(yùn)營(yíng)商在占領(lǐng)主SIM卡后猜旬,對(duì)SIM卡2的欲望越來(lái)越大脆栋,獲取SIM卡2的信息的需求也變大,只有知己知彼洒擦,才能占得先機(jī)椿争。

這里簡(jiǎn)單介紹一下 Android 手機(jī)如何讀取 Sim 卡信息

關(guān)鍵類

必要權(quán)限:
{@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}

一、 一個(gè)重要的表

  • siminfo telephony.db 中記錄Sim卡信息的表熟嫩,可以從建表的 sql 語(yǔ)句中讀取該表的信息
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 - 沒(méi)插入、 0 - 卡槽1 掸茅、1 - 卡槽2
    display_name TEXT,  //顯示名
    carrier_name TEXT,  //運(yùn)行商
    name_source INTEGER DEFAULT 0,  //顯示名的來(lái)源椅邓,0 - 系統(tǒng)分配 1 - 用戶修改
    color INTEGER DEFAULT 0,  //顯示顏色,沒(méi)什么用
    number TEXT,  //電話號(hào)碼
    display_number_format INTEGER NOT NULL DEFAULT 1,  //
    data_roaming INTEGER DEFAULT 0,  //是否支持漫游
    mcc INTEGER DEFAULT 0,  //移動(dòng)國(guó)家碼
    mnc INTEGER DEFAULT 0  //移動(dòng)網(wǎng)絡(luò)碼
);

可以通過(guò) ContentProvider 進(jìn)行查詢

    public void testReadNameByPhone() {
        Uri uri = Uri.parse("content://telephony/siminfo"); //訪問(wèn)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();
        }
    }

二倦蚪、 二個(gè)重要的類

  • SubscriptionManager 讀取 siminfo 數(shù)據(jù)庫(kù)的信息管理類希坚,僅支持5.1版本以上
  • TelephonyManager 手機(jī)SIM信息管理類

三、 三個(gè)重要id

  • slotId 卡槽ID 雙卡的基本就是0,1

  • phoneId 電話ID 與 slotId 基本相同陵且,雙卡基本都是0,1裁僧,不過(guò)在源碼 getDeviceId 方法中有個(gè)FIXME注釋
    // FIXME this assumes phoneId == slotId
    因此Android源碼也只是假設(shè) phoneId == slotId,可能會(huì)在以后修改 phoneId

  • subId 在 TelephonyManager 類中最常用的ID慕购,但也是最不固定的ID聊疲,隨著使用手機(jī)號(hào)碼的增加,這個(gè)值遞增沪悲,其實(shí)本質(zhì)就是siminfo的_id

讀取信息方法

一获洲、 版本超過(guò)5.1(API 22)

使用 SubscriptionManager 類進(jìn)行讀取信息

 SubscriptionManager mSubscriptionManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
 mSubscriptionManager.getActiveSubscriptionInfoCountMax();//手機(jī)SIM卡數(shù)
 mSubscriptionManager.getActiveSubscriptionInfoCount();//手機(jī)使用的SIM卡數(shù)
 List<SubscriptionInfo> activeSubscriptionInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();//手機(jī)SIM卡信息

通過(guò) SubscriptionInfo 的實(shí)例進(jìn)行讀取信息,對(duì)應(yīng)的是 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;
}

該類沒(méi)有常用的手機(jī)IMEI值和IMSI值殿如,這個(gè)值可以通過(guò) TelephonyManager 進(jìn)行讀取贡珊,不過(guò)需要通過(guò)反射,具體可見(jiàn)下方關(guān)于 TelephonyManager 的介紹

telephonyManager.getDeviceId(subscriptionInfo.getSimSlotIndex());//通過(guò)slotID讀取IMEI值涉馁,版本必須高于6.0(API 23)
telephonyManager.getSubscriberId(subscriptionInfo.getSubscriptionId()) {;//通過(guò)subId讀取IMSI值门岔,版本必須高于6.0(API 23)

二、版本低于5.1版本

使用 TelephonyManager 讀取SIM卡信息:

TelephonyManager 僅能讀取默認(rèn)卡的信息烤送,幾乎所有的通過(guò)ID讀取副卡信息的接口都添加了@hide 注釋寒随,無(wú)法使用,因此只能通過(guò)反射的機(jī)制進(jìn)行調(diào)取

2.1 TelephonyManager 讀取主卡信息

TelephonyManager telephonyManager = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE));
telephonyManager.getSimOperatorName();  //運(yùn)營(yíng)商信息
telephonyManager.getNetworkOperatorName(); //網(wǎng)絡(luò)顯示名
telephonyManager.getLine1Number();  //電話號(hào)碼
telephonyManager.getDeviceId();  //IMEI值
telephonyManager.getSubscriberId();  //IMSI值

2.2 通過(guò)反射讀取副卡信息

讀取副卡信息大多只需要1個(gè)參數(shù),slotId 或者 subId妻往,源碼方法如下(我們主要關(guān)心的是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 的參數(shù),無(wú)法直接調(diào)用讯泣,這里就需要用到反射:

    /**
     * 通過(guò)反射調(diào)取@hide的方法
     *
     * @param predictedMethodName 方法名
     * @param id 參數(shù)
     * @return 返回方法調(diào)用的結(jié)果
     * @throws MethodNotFoundException 方法沒(méi)有找到
     */
    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;
    }

    /**
     * 通過(guò)反射調(diào)取@hide的方法
     *
     * @param predictedMethodName 方法名
     * @return 返回方法調(diào)用的結(jié)果
     * @throws MethodNotFoundException 方法沒(méi)有找到
     */
    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;
    }

現(xiàn)在就可以通過(guò)反射進(jìn)行調(diào)用方法讀取數(shù)據(jù)了

//IMEI纫普,通過(guò)slotId,比較準(zhǔn)確
getReflexMethodWithId("getDeviceId",“1”);

//IMSI,通過(guò)subId判帮,很不準(zhǔn)確局嘁,保障準(zhǔn)確率有兩種方式
//1. 通過(guò) SubscriptionInfo.getSubscriptionId() 獲得準(zhǔn)確的 subId 進(jìn)行調(diào)用
//2. 從0開(kāi)始遍歷20次或更多次,找到不等于主卡IMSI的值
getReflexMethodWithId("getSubscriberId",“1”);

//運(yùn)營(yíng)商信息晦墙,PhoneId,基本準(zhǔn)確
getReflexMethodWithId(this, "getSimOperatorNameForPhone", “1”) 

//subId肴茄,很不準(zhǔn)確
getReflexMethodWithId(this, "getSimCountryIso",“1”); 

//電話號(hào)碼晌畅,subid,很不準(zhǔn)確
getReflexMethodWithId(this, "getLine1Number", “1”);  

特別注意:

  • 電話號(hào)碼和IMSI值都是用過(guò) subId 進(jìn)行讀取的,這個(gè)值很不穩(wěn)定寡痰,不一定就是1或者2抗楔,還有可能是3、4拦坠、5连躏、6,不一定能讀取出來(lái),不過(guò)在5.1版本以上可以通過(guò) subscriptionInfo.getSubscriptionId() 獲得 subId贞滨,可以獲得確定的IMEI值和IMSI值

  • 根據(jù) Android 版本的不同入热,有些方法不一定能反射得到,目前測(cè)試4.4沒(méi)有問(wèn)題

  • 總結(jié)出來(lái)一個(gè)幫助類 PhoneUtils:

public class PhoneUtils {
    /**
     * 構(gòu)造類
     */
    private PhoneUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    /**
     * 判斷設(shè)備是否是手機(jī)
     *
     * @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>需添加權(quán)限 {@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();
    }

    /**
     * 通過(guò)讀取設(shè)備的ROM版本號(hào)晓铆、廠商名勺良、CPU型號(hào)和其他硬件信息來(lái)組合出一串15位的號(hào)碼
     * 其中“Build.SERIAL”這個(gè)屬性來(lái)保證ID的獨(dú)一無(wú)二,當(dāng)API < 9 無(wú)法讀取時(shí)骄噪,使用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>需添加權(quán)限 {@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卡是否準(zhǔn)備好
     *
     * @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卡運(yùn)營(yíng)商名稱
     * <p>中國(guó)移動(dòng)、如中國(guó)聯(lián)通链蕊、中國(guó)電信</p>
     *
     * @return sim卡運(yùn)營(yíng)商名稱
     */
    public static String getSimOperatorName() {
        TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
        return tm != null ? tm.getSimOperatorName() : null;
    }

    /**
     * 獲取Sim卡運(yùn)營(yíng)商名稱
     * <p>中國(guó)移動(dòng)事甜、如中國(guó)聯(lián)通、中國(guó)電信</p>
     *
     * @return 移動(dòng)網(wǎng)絡(luò)運(yùn)營(yíng)商名稱
     */
    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 "中國(guó)移動(dòng)";
            case "46001":
                return "中國(guó)聯(lián)通";
            case "46003":
                return "中國(guó)電信";
            default:
                return operator;
        }
    }

    /**
     * 獲取Sim卡序列號(hào)
     * <p>
     * Requires Permission:
     * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
     *
     * @return 序列號(hào)
     */
    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卡的國(guó)家代碼
     *
     * @return 國(guó)家代碼
     */
    public static String getSimCountryIso() {
        TelephonyManager tm = (TelephonyManager) Utils.getContext().getSystemService(Context.TELEPHONY_SERVICE);
        return tm != null ? tm.getSimCountryIso() : null;
    }

    /**
     * 讀取電話號(hào)碼
     * <p>
     * Requires Permission:
     * {@link android.Manifest.permission#READ_PHONE_STATE READ_PHONE_STATE}
     * OR
     * {@link android.Manifest.permission#READ_SMS}
     * <p>
     *
     * @return 電話號(hào)碼
     */
    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;
    }

    /**
     * 獲得卡槽數(shù)滔韵,默認(rèn)為1
     *
     * @return 返回卡槽數(shù)
     */
    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卡使用的數(shù)量
     *
     * @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.版本超過(guò)5.1逻谦,調(diào)用系統(tǒng)方法
            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的系統(tǒng)奏属,首先調(diào)用數(shù)據(jù)庫(kù)跨跨,看能不能訪問(wèn)到
        Uri uri = Uri.parse("content://telephony/siminfo"); //訪問(wèn)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.通過(guò)反射讀取卡槽信息,最后通過(guò)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;
    }

    /**
     * 通過(guò)反射獲得SimInfo的信息
     * 當(dāng)index為0時(shí),讀取默認(rèn)信息
     *
     * @param index 位置,用來(lái)當(dāng)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,比較準(zhǔn)確
            simInfo.mImsi = getReflexMethodWithId("getSubscriberId", String.valueOf(simInfo.mSimSlotIndex));
            //subId,很不準(zhǔn)確
            simInfo.mCarrierName = getReflexMethodWithId("getSimOperatorNameForPhone", String.valueOf(simInfo.mSimSlotIndex));
            //PhoneId勇婴,基本準(zhǔn)確
            simInfo.mCountryIso = getReflexMethodWithId("getSimCountryIso", String.valueOf(simInfo.mSimSlotIndex));
            //subId忱嘹,很不準(zhǔn)確
            simInfo.mIccId = getReflexMethodWithId("getSimSerialNumber", String.valueOf(simInfo.mSimSlotIndex));
            //subId,很不準(zhǔn)確
            simInfo.mNumber = getReflexMethodWithId("getLine1Number", String.valueOf(simInfo.mSimSlotIndex));
            //subId耕渴,很不準(zhǔn)確
        } catch (MethodNotFoundException ignored) {
        }
        return simInfo;
    }

   /**
     * 通過(guò)反射調(diào)取@hide的方法
     *
     * @param predictedMethodName 方法名
     * @return 返回方法調(diào)用的結(jié)果
     * @throws MethodNotFoundException 方法沒(méi)有找到
     */
    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;
    }

    /**
     * 通過(guò)反射調(diào)取@hide的方法
     *
     * @param predictedMethodName 方法名
     * @param id 參數(shù)
     * @return 返回方法調(diào)用的結(jié)果
     * @throws MethodNotFoundException 方法沒(méi)有找到
     */
    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 {
        /** 運(yùn)營(yíng)商信息:中國(guó)移動(dòng) 中國(guó)聯(lián)通 中國(guó)電信 */
        public CharSequence mCarrierName;
        /** 卡槽ID拘悦,SimSerialNumber */
        public CharSequence mIccId;
        /** 卡槽id, -1 - 沒(méi)插入橱脸、 0 - 卡槽1 础米、1 - 卡槽2 */
        public int mSimSlotIndex;
        /** 號(hào)碼 */
        public CharSequence mNumber;
        /** 城市 */
        public CharSequence mCountryIso;
        /** 設(shè)備唯一識(shí)別碼 */
        public CharSequence mImei = getIMEI();
        /** SIM的編號(hào) */
        public CharSequence mImsi;

        /**
         * 通過(guò) 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);
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市添诉,隨后出現(xiàn)的幾起案子屁桑,更是在濱河造成了極大的恐慌,老刑警劉巖栏赴,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蘑斧,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡须眷,警方通過(guò)查閱死者的電腦和手機(jī)竖瘾,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)花颗,“玉大人捕传,你說(shuō)我怎么就攤上這事±┤埃” “怎么了庸论?”我有些...
    開(kāi)封第一講書人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)今野。 經(jīng)常有香客問(wèn)我葡公,道長(zhǎng),這世上最難降的妖魔是什么条霜? 我笑而不...
    開(kāi)封第一講書人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任催什,我火速辦了婚禮,結(jié)果婚禮上宰睡,老公的妹妹穿的比我還像新娘蒲凶。我一直安慰自己,他們只是感情好拆内,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布旋圆。 她就那樣靜靜地躺著,像睡著了一般麸恍。 火紅的嫁衣襯著肌膚如雪灵巧。 梳的紋絲不亂的頭發(fā)上搀矫,一...
    開(kāi)封第一講書人閱讀 51,443評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音刻肄,去河邊找鬼瓤球。 笑死,一個(gè)胖子當(dāng)著我的面吹牛敏弃,可吹牛的內(nèi)容都是我干的卦羡。 我是一名探鬼主播,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼麦到,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼绿饵!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起瓶颠,我...
    開(kāi)封第一講書人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤拟赊,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后粹淋,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體要门,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年廓啊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片封豪。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡谴轮,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出吹埠,到底是詐尸還是另有隱情第步,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布缘琅,位于F島的核電站粘都,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏刷袍。R本人自食惡果不足惜翩隧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望呻纹。 院中可真熱鬧堆生,春花似錦、人聲如沸雷酪。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)哥力。三九已至蔗怠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背寞射。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工渔工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人怠惶。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓涨缚,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親策治。 傳聞我的和親對(duì)象是個(gè)殘疾皇子脓魏,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)通惫,斷路器茂翔,智...
    卡卡羅2017閱讀 134,656評(píng)論 18 139
  • Android5.0開(kāi)始支持雙卡了。另外履腋,對(duì)于雙卡的卡信息的管理珊燎,也有了實(shí)現(xiàn),盡管還不是完全徹底完整遵湖,如卡的slo...
    rayxiang閱讀 1,094評(píng)論 0 0
  • 一悔政、環(huán)境 安卓系統(tǒng):4.2 操作系統(tǒng):Win 8.1 工具:Android Studio 二、SQLite操作 新...
    谷鴿不愛(ài)吃稻谷閱讀 573評(píng)論 0 2
  • 國(guó)家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報(bào)批稿:20170802 前言: 排版 ...
    庭說(shuō)閱讀 10,967評(píng)論 6 13
  • 開(kāi)學(xué)啦延旧,學(xué)期伊始谋国,每天都有忙不完的事情。有朋友提議去放松一下心情迁沫。雖然事務(wù)多多芦瘾,戶外活動(dòng)確實(shí)太有吸引力了。我們放下...
    蘭澤君閱讀 713評(píng)論 5 10