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 explanation 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.
}
在这里,我正在检查是否使用“ContextCompat”授予了permisssion,并且我再次使用ActvityCompat请求权限... 我需要知道这两种方法有什么区别?
答案 0 :(得分:6)
文档说:
要检查您是否拥有权限,请致电
ContextCompat.checkSelfPermission()
方法。例如,这个 片段显示如何检查活动是否具有写入权限 日历:int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.WRITE_CALENDAR);
这意味着您要检查您的应用程序是否具有使用危险权限的权限。
activitycompat.requestPermission()
用于请求用户授予我们使用危险权限的权限。
所以这是片段:
//checking if you have the permission
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// you don't have permission so here you will request the user for permission
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an explanation 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.
}
}
我希望这会以某种方式清除你的概念。
答案 1 :(得分:1)
ContextCompat.checkSelfPermission(Context context,String permission)
此方法仅用于检查您是否已获得应用程序的可用权限。
ActivityCompat.requestPermissions(活动活动,String []权限,int reqCode)
此方法用于请求权限。