在申请权限之前一定要在清单配置文件中添加该权限 private static final int MY_PERMISSIONS_REQUEST_RECORD_AUDIO = 1; //随便定义
public void setPermission(){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) //这里申请的是录音权限 != PackageManager.PERMISSION_GRANTED) { //没有权限的时候去申请 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, MY_PERMISSIONS_REQUEST_RECORD_AUDIO); }else{ //正常执行任务 }} //权限请求结果
@Overridepublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case MY_PERMISSIONS_REQUEST_RECORD_AUDIO : if (grantResults.length > 0 && grantResults[0] ==PackageManager.PERMISSION_GRANTED){ //权限申请成功 } else { //申请失败 ToastUtils.show(this,"请到授权管理中开启"); } break; default: break; }}
时间: 2024-10-29 19:12:00