fun getPhoneNumber(): ArrayList<String> {
val phoneList = arrayListOf<String>()
try {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
val sm =
getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
val subList = sm.activeSubscriptionInfoList
subList?.forEach {
val rawPhone = it.number
if (!rawPhone.isNullOrEmpty()){
val length = rawPhone.length
if (length > 11){
phoneList.add(rawPhone.substring(length - 11))
}else{
phoneList.add(rawPhone)
}
}
}
} else {
val tm =
getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
phoneList.add(tm.line1Number)
}
}catch (e: SecurityException){
Log.e("aa", "**获取手机号码异常:${e.message}")
}
return phoneList
}
1、需要权限
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
2、telephonyManager.getLine1Number()
(1)在Q以后版本无法获取到手机号
(2)双卡手机,卡1存在则返回卡1号码,否则返回卡2号码
3、SubscriptionInfo.number()需api22及以上版本