Android6.0更新后,推出了动态权限管理。以往我们将涉及到的权限都写在清单文件中直接进行配置,对于一些敏感的权限,写程序时必须在程序中进行声明。相机和相册选择图片都涉及用户隐私的敏感权限,所以必须在程序中进行声明。
自定义一个点击事件 :
imgPhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 23) {
int permission = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.CAMERA);
if (permission == PackageManager.PERMISSION_GRANTED) {
startCamera();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("提示");
builder.setMessage("是否开启相机权限?");
builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 0);
}
});
builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), "您拒绝了开启相机权限", Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
} else {
startCamera();
}
}
});
事件回调(权限申请完回调)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (permissions[0].equals(Manifest.permission.CAMERA)) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "已授权", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "授权失败", Toast.LENGTH_SHORT).show();
}
}
}
调用开启相机方法
private void startCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addCategory("android.intent.category.DEFAULT");
startActivityForResult(intent, 1);
}
动态和静态添加权限都需要配置清单文件!
<uses-permission android:name="android.permission.CAMERA"/>