如何反射SubscriptionManager和TelephonyManager获取其方法

        mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (mTelephonyManager == null) {
            throw new Error("telephony manager is null");
        }
       
        mSubscriptionManager = SubscriptionManager.from(mContext);

举个栗子,获取SubscriptionManagergetSubId(slotId) 和TelephonyManager 的getSimSerialNumber(int subId)

    private static int[] getSubId(int slotId) {
        Method declaredMethod;
        int[] subArr = null;
        try {
            declaredMethod = Class.forName("android.telephony.SubscriptionManager").getDeclaredMethod("getSubId", new Class[]{Integer.TYPE});
            declaredMethod.setAccessible(true);
            subArr = (int[]) declaredMethod.invoke(mSubscriptionManager, slotId);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            declaredMethod = null;
        } catch (IllegalArgumentException e2) {
            e2.printStackTrace();
            declaredMethod = null;
        } catch (NoSuchMethodException e3) {
            e3.printStackTrace();
            declaredMethod = null;
        } catch (ClassCastException e4) {
            e4.printStackTrace();
            declaredMethod = null;
        } catch (IllegalAccessException e5) {
            e5.printStackTrace();
            declaredMethod = null;
        } catch (InvocationTargetException e6) {
            e6.printStackTrace();
            declaredMethod = null;
        }
        if (declaredMethod == null) {
            subArr = null;
        }
        MLog.d("getSubId = " + subArr[0]);
        return subArr;
    }

    private String getSimSerialNumber(int subId) {
        Method method;
        String status = null;
        try {
            method = mTelephonyManager.getClass().getMethod("getSimSerialNumber", int.class);
            method.setAccessible(true);
            status = String.valueOf(method.invoke(mTelephonyManager, subId));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        MLog.d("getSimSerialNumber = " + status);
        return status;
    }


你可能感兴趣的:(Telephony)