Android 获取手机号码

部分应用需要获取手机的号码,可以采用代码的方式来获取。

代码如下:

public String getNativePhoneNumber() {
    telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        //
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return null;
    }
    nativePhoneNumber = telephonyManager.getLine1Number();
    if(nativePhoneNumber != null && nativePhoneNumber.length() != 0){
        newNativePhoneNumber = nativePhoneNumber.substring(1,nativePhoneNumber.length());
    }
    Log.d(TAG, "getNativePhoneNumber++++++++++++: " + nativePhoneNumber);
    return newNativePhoneNumber;
}

需要在AndroidManifest中设置权限。并在代码中动态获取权限。


动态获取权限使用

rxpermissions2

动态获取

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'io.reactivex.rxjava2:rxjava:2.0.5'
compile 'com.tbruyelle.rxpermissions2:rxpermissions:0.9.3@aar'

获取的代码如下:

public void requestPermissions() {
    RxPermissions rxPermission = new RxPermissions(MainActivity.this);
    rxPermission
            .requestEach(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_SMS)
            .subscribe(new Consumer<Permission>() {
                @Override
                public void accept(Permission permission) throws Exception {
                    if (permission.granted) {
                        // 用户已经同意该权限
                        getNativePhoneNumber();
                        Log.d(TAG, permission.name + " is granted.");
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限,没有选中『不再询问』(Never ask again,那么下次再次启动时,还会提示请求权限的对话框
                        Log.d(TAG, permission.name + " is denied. More info should be provided.");
                    } else {
                        // 用户拒绝了该权限,并且选中『不再询问』
                        Log.d(TAG, permission.name + " is denied.");
                    }
                }
            });
}

猜你喜欢

转载自blog.csdn.net/mlsnatalie/article/details/80678313