以编程方式检索手机号码?

时间:2018-04-30 16:50:18

标签: java android-studio

public void get(View view) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted
            phone.setText("Not granted");
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_PHONE_STATE},
                    MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        }
        else {
            phone.setText("Granted");
            TelephonyManager mTelephonyMgr;
            mTelephonyMgr = (TelephonyManager) getSystemService
                    (Context.TELEPHONY_SERVICE);



       String number = mTelephonyMgr.getLine1Number();
        //String number = getMyPhoneNO();
        if (number.matches("")) {
            phone.setText("There is no number");
        }
        else {
            phone.setText(number);
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试提及在AndroidManifest.xml中读取手机状态所需的权限

例如。

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

这授予您的应用程序可以读取Android手机状态的权限