1.我们需要在用到权限的地方,每次都检查是否APP已经拥有权限,比如我们有一个下载功能,需要写SD卡的权限,我们在写入之前检查是否有WRITE_EXTERNAL_STORAGE权限,没有则申请权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //申请WRITE_EXTERNAL_STORAGE权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_REQUEST_CODE); }
2.
请求权限后,系统会弹出请求权限的Dialog 用户选择允许或需要后,会回调onRequestPermissionsResult方法, 该方法类似于onActivityResult @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); doNext(requestCode,grantResults); }
3.
我们接着需要根据requestCode和grantResults(授权结果)做相应的后续处理 private void doNext(int requestCode, int[] grantResults) { if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted } else { // Permission Denied } } }
Android6.0动态权限申请(6.0普及后会广泛使用)
最新推荐文章于 2022-01-21 01:10:52 发布