permission_service.dart 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import 'dart:io';
  2. import 'package:permission_handler/permission_handler.dart';
  3. enum PermissionResult {
  4. granted,
  5. denied,
  6. permanentlyDenied,
  7. }
  8. enum PermissionType {
  9. camera,
  10. gallery,
  11. microphone,
  12. bluetooth,
  13. }
  14. class PermissionService {
  15. /// 对外统一入口
  16. static Future<PermissionResult> request(
  17. PermissionType type,
  18. ) async {
  19. final permission = _mapPermission(type);
  20. final status = await permission.status;
  21. if (status.isGranted) {
  22. return PermissionResult.granted;
  23. }
  24. final result = await permission.request();
  25. if (result.isGranted) {
  26. return PermissionResult.granted;
  27. }
  28. if (result.isPermanentlyDenied) {
  29. return PermissionResult.permanentlyDenied;
  30. }
  31. return PermissionResult.denied;
  32. }
  33. /// 跳转系统设置
  34. static Future<void> openSetting() async {
  35. await openAppSettings();
  36. }
  37. /// 权限映射(平台差异处理)
  38. static Permission _mapPermission(PermissionType type) {
  39. switch (type) {
  40. case PermissionType.camera:
  41. return Permission.camera;
  42. case PermissionType.microphone:
  43. return Permission.microphone;
  44. case PermissionType.gallery:
  45. if (Platform.isAndroid) {
  46. return Permission.photos;
  47. }
  48. return Permission.photos;
  49. case PermissionType.bluetooth:
  50. if (Platform.isAndroid) {
  51. return Permission.bluetoothConnect;
  52. }
  53. return Permission.bluetooth;
  54. }
  55. }
  56. }