How to get the phone's native number on Android
Reflect TelephoneManager to get the local number. Note that some SIM cards cannot be obtained without writing the interface. This interface is only suitable for Android 5.0 or above.
public String getMsisdn(int slotId) { return getLine1NumberForSubscriber(getSubIdForSlotId(slotId)); }
Permissions
<uses-permission android:name=".READ_PHONE_STATE"/>
public class RegisterMessage { private static Context mContext; private static TelephonyManager mTelephonyManager; private ConnectivityManager mConnMngr; private static SubscriptionManager mSubscriptionManager; public RegisterMessage(Context context) { mContext = context; mTelephonyManager = (TelephonyManager) (Context.TELEPHONY_SERVICE); if (mTelephonyManager == null) { throw new Error("telephony manager is null"); } mConnMngr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); mSubscriptionManager = (mContext); }
public String getMsisdn(int slotId) {//slotId 0 is card 1, 1 is card 2 return getLine1NumberForSubscriber(getSubIdForSlotId(slotId)); } rivate int getSubIdForSlotId(int slotId) { int[] subIds = getSubId(slotId); if (subIds == null || < 1 || subIds[0] < 0) { return -1; } ("getSubIdForSlotId = "+subIds[0]); return subIds[0]; } private static int[] getSubId(int slotId) { Method declaredMethod; int[] subArr = null; try { declaredMethod = ("").getDeclaredMethod("getSubId", new Class[]{}); (true); subArr = (int[]) (mSubscriptionManager,slotId); } catch (ClassNotFoundException e) { (); declaredMethod = null; } catch (IllegalArgumentException e2) { (); declaredMethod = null; } catch (NoSuchMethodException e3) { (); declaredMethod = null; } catch (ClassCastException e4) { (); declaredMethod = null; } catch (IllegalAccessException e5){ (); declaredMethod = null; }catch (InvocationTargetException e6){ (); declaredMethod = null; } if(declaredMethod == null) { subArr = null; } ("getSubId = "+subArr[0]); return subArr; } private String getLine1NumberForSubscriber(int subId){ Method method; String status = null; try { method = ().getMethod("getLine1NumberForSubscriber", ); (true); status = ((mTelephonyManager, subId)); } catch (NoSuchMethodException e) { (); } catch (IllegalAccessException e) { (); } catch (IllegalArgumentException e) { (); } catch (InvocationTargetException e) { (); } ("getLine1NumberForSubscriber = "+status); return status; }
If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!