我想以编程方式获取Android Studio中的电话号码。 我试过这个:(并且它导致崩溃)
TelephonyManager tMgr =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
有什么问题?获取电话号码的其他任何方式?
答案 0 :(得分:1)
我认为你需要<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
private String getMyPhoneNO() {
TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
return mPhoneNumber;
}
与
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
} else {
String phoneNumber = getMyPhoneNO();
}
在Activity / Fragment中
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
String phoneNumber = getMyPhoneNO();
}
}
}
答案 1 :(得分:0)
您需要添加
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
为新的Android版本显示+请求运行时权限。
https://developer.android.com/training/permissions/requesting.html
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
否则你可以在stacktrace中看到解释错误。