一、检查应用是否拥有某个权限
在android6.0以前的方式
PackageManager pm = getPackageManager();
boolean permission = (PackageManager.PERMISSION_GRANTED ==pm.checkPermission("android.permission.RECORD_AUDIO", "packageName"));
在android6.0以后的方式
boolean permission = ContextCompat.checkSelfPermission(mContext, permission) == PackageManager.PERMISSION_DENIED;
或者还可以用V4包中提供的函数
boolean permission = PermissionChecker.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
在6.0以前,很多权限在Manifest.xml中声明了就代表应用已经拥有了该项权限,所以即使去《设置》中手动静止该项权限,ContextCompat.checkSelfPermission函数返回的值永远都等于PackageManager.PERMISSION_DENIED。所以在6.0以前的系统如果手动静止了, 就没法用这个函数来做判断,只能再去手动打开权限。
二、申请权限
ActivityCompat.requestPermissions(thisActivity,new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
处理权限申请回掉
@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;
}
}
}
当用户拒绝过一次权限申请了,当再一次申请权限时,需要给用户一个解释为什么要申请该权限,调用以下代码
ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,Manifest.permission.READ_CONTACTS)
例如:
// 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);
}
结语:随着版本的升级,Google在android手机的安全处理上也在不断的完善,更好的保护用户手机的安全。 用户的安全是保障了,程序员的工作复杂程度也会越来越高,需要不断的更新自己的知识库,才能不被淘汰,加油!!