做项目看到有个demo调用相机完全没有在配置文件申请权限 后来一看才发现其实是调用的系统相机 并不是自己应用调用相机
在执行运行时权限申请的同时想一下是否真的有必要,想一下使用Intent的方式启动其他应用是否可以达到需求,比如ACTION_IMAGE_CAPTURE,是直接申明CAMERA的权限自己做一个照相机还是发送ACTION_IMAGE_CAPTURE请求让别的应用处理并在onActivityResult()返回值更方便
记录一下具体调用6.0权限的方法
第一.判断
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
第二.如果是android6.0以上的系统,则检查是否获取授权
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_CALENDAR);
如果返回值为PackageManager.PERMISSION_GRANTED,则可以继续之后的操作,如果返回值为PERMISSION_DENIED,则代表没有授权该权限。
第三.shouldShowRequestPermissionRationale()可以得到是否需要弹出一个解释申请该权限的提示给用户,如果为true,则可以弹。
第四.请求该权限
示例如下:
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
} else {
执行获取权限后的操作
}
成功获取权限后 在回调里调用我们自己的代码
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}