How to get Mobile number from SIM card in Android Programmatically using kotlin language?

I tried using below piece of code but it is not giving me the number. Your information would be great help.

Code below:

val subscription =SubscriptionManager.from(context).activeSubscriptionInfoList
for (subscriptionInfo in subscription)
{
   val number = subscriptionInfo.number
   Log.e("Test", " Number is  " + number)
}

Solution 1:

Correct way to get IMEI Number KOTLIN

try{
    val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
    val IMEI = tm.getImei()
    if (IMEI != null)
        Toast.makeText(this, "IMEI number: " + IMEI,
                Toast.LENGTH_LONG).show()

}catch (ex:Exception){
    Log.e("",ex.message)
}

Including asking for Permission

  if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_PHONE_STATE)) {
    } else { ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.READ_PHONE_STATE), 2) } }

Don't forget AndroidManifest.xml

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Solution 2:

Taken from this answer and translated to kotlin:

Getting the Phone Number, IMEI, and SIM Card ID

val tm = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager

// For SIM card, use the getSimSerialNumber()    
//---get the SIM card ID---
val simID = tm.simSerialNumber
if (simID != null)
    Toast.makeText(this, "SIM card ID: " + simID,
            Toast.LENGTH_LONG).show()

Phone number of your phone, use the getLine1Number() (some device's dont return the phone number)

//---get the phone number---
val telNumber = tm.line1Number
if (telNumber != null)
    Toast.makeText(this, "Phone number: " + telNumber,
            Toast.LENGTH_LONG).show()


// IMEI number of the phone, use the getDeviceId()
//---get the IMEI number---
val IMEI = tm.deviceId
if (IMEI != null)
    Toast.makeText(this, "IMEI number: " + IMEI,
            Toast.LENGTH_LONG).show()

Permissions needed:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Please note that some devices could not return the phone number due to its internal implementation.