安卓请求权限还要注意的那一丢丢事儿
[预期]
在用户拒绝了权限的情况下,页面上还有一个按钮可以点击继续申请权限,提升用户体验
[相关代码]
按钮点击:
override fun onClick(v: View?) {
Log.e("111111","onClick,id = ${v?.id}")
when(v?.id){
R.id.btn_permission->requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE)
}
}
权限申请结果判断:
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
Log.e("111111","onRequestPermissionsResult${grantResults.contentToString()}")
if (requestCode == PERMISSIONS_REQUEST_CODE) {
if (grantResults.contains(PackageManager.PERMISSION_DENIED)) {
Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show()
} else {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate(
PermissionsFragmentDirections.actionPermissionsFragmentToBlankFragment2())
}
}
}
[然而]
用户快速点击的情况下,onRequestPermissionsResult结果是这样的。。
E/111111: onRequestPermissionsResult[]
[为什么]
先上个代码,这是Activity请求权限的时候如果版本>23的时候调用的方法
public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
if (requestCode < 0) {
throw new IllegalArgumentException("requestCode should be >= 0");
}
// ↓↓↓↓↓↓↓↓↓关键代码在这里 ↓↓↓↓↓↓↓↓↓↓
if (mHasCurrentPermissionsRequest) {
Log.w(TAG, "Can request only one set of permissions at a time");
// Dispatch the callback with empty arrays which means a cancellation.
onRequestPermissionsResult(requestCode, new String[0], new int[0]);
return;
}
// ↑↑↑↑↑↑↑↑↑关键代码在这里↑↑↑↑↑↑↑↑↑↑↑
Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
mHasCurrentPermissionsRequest = true;
}
[原来]
权限请求结果返回前,再次请求就会如此返回。
[所以]
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
Log.e("111111","onRequestPermissionsResult${grantResults.contentToString()}")
if (requestCode == PERMISSIONS_REQUEST_CODE) {
if(grantResults.contains(PackageManager.PERMISSION_DENIED)||grantResults.isEmpty()) {
Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show()
} else {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate(
PermissionsFragmentDirections.actionPermissionsFragmentToBlankFragment2())
}
}
}
判断一下grantResult的长度吧。
这是一个懒人万年一更。。。。。。