Android初学者很容易在应用的权限上感觉无所适从,掌握不到要点。
Api23之前的应用权限,只需要在AndroidManifest.xml中声名应用所需的权限。用户在安装时,系统会展示此应用所需要的权限,当且仅当用户允许了所有权限,应用才会安装在系统中。并且,只要应用在AndroidManifest.xml文件中声名了该文件,那么使用方法checkPermission得到的结果就一定是granted(即存在权限)。如果用户在应用安装后,手动至应用管理中关闭部分权限,那么我们是无法通过“正规渠道”来排查到那部分应用的开关状态。那么此时只能通过异常(相机无法开启)或者空数据(获取本地图片时为空,文件读取权限)等侧面方式来提示用户无相关权限。
而在Google在Android SDK Api23(含)之后就采用了动态权限管理机制,一些涉及用户安全的权限不仅仅需要在AndroidManifest.xml文件中声名,还需要在运行时进行请求,让用户同意。如果用户不同意,那么checkPermission方法会得到ungranted的结果,表明该权限未开启。可以通过requestPermission方法来获取权限,并通过OnRequestPermissionResult方法来获取权限申请结果。Activity与Fragment各自有相应的requestPermission与OnRequestPermissionResult方法,如果使用Activity的requestPermission方法,则使用Fragment的OnRequestPermissionResult方法无法获取权限申请结果;反之亦然。
举栗子-此栗子直接摘自google官方文档,可自行扩展:
// 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.
}
}
@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
}
}