其实网上的文章都很详细比如文章1(http://www.voidcn.com/article/p-ehdfbrsl-nh.html )文章2(http://www.voidcn.com/article/p-ehdfbrsl-nh.html )。 其实实现过程都大同小异,我们主要来看我遇到得的问题,当然这些问题都是在6.0以上的版本出现的问题,之前的都没有。
安卓6.0以上获取摄像机权限
在最开始我们在AndroidManifest.xml文件中添加获取相机权限,如下
<uses-permission android:name="android.permission.CAMERA"/>
然后运行程序第一次并没有提示我获得相机权限,然后再点击打开相机闪退,妈耶。然后就查资料说,相机这类权限属于危险级,需要动态请求。所以这里就开始编写动态请求,网上蛮多文章说这个的,大多都需要使用其他什么插件得的。官方给出的代码:
// 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.
}
}
更多详细的可以看看官网文档(https://developer.android.com/training/permissions/requesting)。 这里用的