1
如何在android studio中获取手机号码?我尝试使用此代码获取手机号码,但返回值为空。如何在android studio中获取手机号码?
TelephonyManager tpm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String number = tpm.getLine1Number();
如何在android studio中获取手机号码?我尝试使用此代码获取手机号码,但返回值为空。如何在android studio中获取手机号码?
TelephonyManager tpm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String number = tpm.getLine1Number();
这是https://developer.android.com/reference/android/telephony/TelephonyManager.html
getLine1Number
字符串getLine1Number相关documantation()返回第1行, 例如,MSISDN对于GSM电话的电话号码串。如果它不是 ,则返回null。
默认的短信应用程序也可以使用它。
需要READ_PHONE_STATE,READ_SMS或READ_PHONE_NUMBERS 权限。
此外,如果您使用的是Android 6.0或更高版本,请添加以下代码。 此代码检查应用程序是否有权读取用户的联系人,也可以在必要时向用户请求权限。试试这个
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}
你添加了 权限吗? –
coderaizer
我还添加了 权限。 –
user8339581
你正在尝试的Android版本是什么? – coderaizer