Android6.0动态申请权限

背景:最近有一个需求是在添加联系人的时候,需要动态申请权限跳到通讯录页面选择一个联系人之后拿到联系人的电话号码。

走过的坑:在开始的时候总是弹不出系统权限框,而是会直接跳到通讯录,默认已经获取到了权限。

解决:在build.gradle中targetSdkVersion 22改成23.

代码:

(1)申请权限的点击事件

View.OnClickListener addAddressListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //版本判断,当手机系统大于 23 时,才有必要去判断权限是否获取
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(AddOrEditContactAct.this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED) {
                    //沒有获取到权限
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(AddOrEditContactAct.this, Manifest.permission.READ_CONTACTS)) {//禁止权限并不再提示
                        showDialogTipUserRequestPermission("为保证您此功能的正常使用,需开启通讯录授权");
                    } else {//禁止权限
                        ActivityCompat.requestPermissions(AddOrEditContactAct.this, new String[]{Manifest.permission.READ_CONTACTS}, PERMISSION_CONTACT_REQUEST_CODE);
                    }
                } else { //已经授权,跳转到通讯录界面
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, INTENT_REQUEST_CODE_CONTACT);
                }
            }
        };

(2)申请权限的回调

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_CONTACT_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //已经授权,跳转到通讯录界面
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, INTENT_REQUEST_CODE_CONTACT);
            } else{//禁止授权,不操作
            }
        }
    }

(3)从通讯录回来的回调

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case INTENT_REQUEST_CODE_CONTACT:
                if (resultCode == Activity.RESULT_OK) {
                    if (data == null) {
                        return;
                    }
                    Uri uri = data.getData();
                    String[] contacts = PhoneUtil.getPhoneContacts(uri, this);
                    String contactNumber = contacts[1].replace(" ", "").replace("-","");//有一些系统中电话号码会用空格或者“-”去分隔,我们需要把它过滤掉
                    if (contacts != null) {
                        if (contactType == 1) {
                            mEtContactMobile.setText(contactNumber);
                        } else {
                            if (contactNumber.length() > 8) {
                                mEtPhoneNumber.setText(contactNumber.substring(contactNumber.length() - 8));
                            } else {
                                mEtPhoneNumber.setText(contactNumber);
                            }
                        }
                    } else {
                        showDialogTipUserRequestPermission("未获取到数据,请检查是否为APP开启通讯录授权");
                    }
                }
                break;
            default:
                break;
        }
    }

(4)通讯录权限被禁止后弹框

    private void showDialogTipUserRequestPermission(String msg) {
        AlertDialogUtil.alert(this, "", msg, "取消", "去设置",
                null, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //系统应用权限设置
                        Intent localIntent = new Intent();
                        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (Build.VERSION.SDK_INT >= 9) {
                            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
                        } else if (Build.VERSION.SDK_INT <= 8) {
                            localIntent.setAction(Intent.ACTION_VIEW);
                            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
                        }
                        startActivity(localIntent);
                    }
                });
    }

(5)获取通讯录信息

    public static String[] getPhoneContacts(Uri uri, Context context) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = context.getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            if (!cursor.moveToFirst()) {
                return null;
            }
            //取得联系人姓名
            contact[0] = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

你可能感兴趣的:(Android6.0动态申请权限)