如何使用kotlin语言以编程方式从Android中的SIM卡获取手机号码?

时间:2018-01-12 09:36:43

标签: android kotlin

我尝试使用下面的代码,但它没有给我这个号码。您的信息将会很有帮助。

以下代码:

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

2 个答案:

答案 0 :(得分:3)

获取IMEI号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)
}

包括要求许可

  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) } }

不要忘记AndroidManifest.xml

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

答案 1 :(得分:0)

取自this answer并翻译为kotlin:

获取电话号码,IMEI和SIM卡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()

手机的电话号码,请使用getLine1Number()(某些设备不会返回电话号码)

//---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"/>

请注意,由于内部实施,某些设备无法返回电话号码