Android: How to get cellphone number from SIM

Posted on


In some register forms you need to get the phone number in order to avoid that some users enters some invalid phones. So in order to achieve this you could detect the number from the SIM. The tricky point is that some Carriers does not have such info updated on the SIM, so in this scenarios this will not work.
Here there is a snapshot in which place you need to take a look to see if the phone is correct in the cellphone.
As you can see here the ‘My phone number’ is Unknown, so I do have a Carrier which does not update correctly the phone in the SIM 🙂
In this scenario we do have register the phone.
The code in order to grab the information of the SIM in case the info is there is the following:

 public static String getSIMCardPhoneNumber(Context context){
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String phone = tm.getLine1Number();
        String dId = tm.getSimSerialNumber();
        Log.d("SIM", "Phone number: " + phone);
        Log.d("SIM", "Did number: " + dId);
        return tm.getLine1Number();

I hope this helps you!

Posted in Android, Java, Mobile, Software DevelopmentTagged , , , ,