Android 6.0 后动态申请权限注意点

1.必须在Manifest文件中静态注册
2.动态申请
if (ContextCompat.checkSelfPermission(this , Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED){
// 当第一次向用户申请权限被拒绝了,这个才会返回true 用于向用户解释为什么需要这个权限 if(ActivityCompat.shouldShowRequestPermissionRationale(this , Manifest.permission.CAMERA)) {
new AlertDialog.Builder(this).setMessage(R.string.granted_camera).setPositiveButton("确定", new DialogInterface.OnClickListener()
{ @Override public void onClick(DialogInterface dialog, int which) { // 申请相机权限 ActivityCompat.requestPermissions(MainActivity.this , new String[]{Manifest.permission.CAMERA} , CAMERA_REQUEST_CODE); } }).show(); } else { ActivityCompat.requestPermissions(this , new String[]{Manifest.permission.CAMERA} , ````CAMERA_REQUEST_CODE); } } else { mTextView.setTextColor(Color.GREEN); mTextView.setText("相机权限已经获取"); } }}

3.获取权限回调
@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_REQUEST_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { mTextView.setTextColor(Color.GREEN); mTextView.setText(R.string.granted_camera); } else { if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { Toast.makeText(this, R.string.deny_camera , Toast.LENGTH_SHORT).show(); } } }}

你可能感兴趣的:(Android 6.0 后动态申请权限注意点)