Android 权限申请java/kotlin
java
private static List<String> sPermissions = new ArrayList<String>(){}; private static int MAX_NUMBER_REQUEST_PERMISSIONS = 2; private static int REQUEST_CODE_PERMISSIONS = 101; private int permissionRequestCount = 0; private boolean hasPermissions = false; /** * 权限申请 */ private void requestPermissionsIfNecessary() { hasPermissions = checkAllPermissions(); if (!hasPermissions) { if (permissionRequestCount < MAX_NUMBER_REQUEST_PERMISSIONS) { permissionRequestCount += 1; ActivityCompat.requestPermissions(this, sPermissions.toArray(new String[0]), REQUEST_CODE_PERMISSIONS); } else { } } } /** * 权限回调 onActivityResult已经废弃 */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_PERMISSIONS) { requestPermissionsIfNecessary(); } } /** * 权限检查 * @return 权限是否申请 */ private Boolean checkAllPermissions() { boolean hasPermissions = true; for (String permission : sPermissions) { hasPermissions = hasPermissions & (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED); } return hasPermissions; }
kotlin
第二种适合单一权限申请
多权限请求请ActivityResultContracts.RequestPermission()改为 ActivityResultContracts.RequestMultiplePermissions
//注册权限回调,它处理用户对系统权限对话框的响应。 保存返回值,ActivityResultLauncher 的一个实例。 // 您可以使用此代码段中所示的 val,也可以在 onAttach() 或 onCreate() 方法中使用 lateinit var。 private val requestPermissionLauncher = registerForActivityResult( ActivityResultContracts.RequestPermission() ) { isGranted: Boolean -> if (isGranted) { // 已授予权限 } else { // 权限请求被拒绝。 } } requestPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
//手动设置权限 fun gotoAppDetailIntent(activity: Activity) { val intent = Intent() intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS intent.data = Uri.parse("package:" + activity.packageName) activity.startActivity(intent) }