如题,最近工作上处理的问题,把解决方案简单逻列出来,供有需要的朋友参考之
解决方案:
1、配置权限
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="32"/>
2、动态申请权限
//相关核心代码,PermissionUtils工具类
private static final String[] RECORDING_PERMISSION_ABOVE_33 = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
//Android 13以后的版本,包括13
private static final String[] RECORDING_PERMISSION_UNDER_33 = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_MEDIA_VIDEO,
Manifest.permission.READ_MEDIA_IMAGES,
Manifest.permission.READ_MEDIA_AUDIO,
};
public static String[] getRecordingPermission() {
return android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
? RECORDING_PERMISSION_ABOVE_33 : RECORDING_PERMISSION_UNDER_33;
}
/**
* 检查多个权限
* <p>
* 检查权限
*
* @param permissions 权限数组
* @param context Context
* @return true 已经拥有所有check的权限 false存在一个或多个未获得的权限
*/
public static boolean checkPermissionsGroup(Context context, String[] permissions) {
for (String permission : permissions) {
if (!checkPermission(context, permission)) {
return false;
}
}
return true;
}
public static void requestPermissions(Activity activity, String[] permissions, int requestCode) {
// 先检查是否已经授权
if (!checkPermissionsGroup(activity, permissions)) {
ActivityCompat.requestPermissions(activity, permissions, requestCode);
}
}
使用示例
String[] permissions = PermissionUtils.getRecordingPermission();
if (!checkResult) {
PermissionUtils.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
} else {
//正常的业务处理逻辑
}