deviceUuid.dart 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // device_info_plus 中 androidInfo.androidId 被移除,无法获取跨应用的设备唯一标识
  2. // 为了代码一致性,iOS 端也不使用 iosInfo.identifierForVendor
  3. // 统一使用 uuid.dart 来随机生成
  4. import 'package:shared_preferences/shared_preferences.dart';
  5. import 'package:uuid/uuid.dart';
  6. class DeviceUuid {
  7. static const String _uuidKey = 'device_uuid';
  8. static String? _cachedUuid;
  9. // 获取或创建 UUID
  10. static Future<String> getUuid() async {
  11. if (_cachedUuid != null) {
  12. return _cachedUuid!;
  13. }
  14. final prefs = await SharedPreferences.getInstance();
  15. String? storedUuid = prefs.getString(_uuidKey);
  16. if (storedUuid == null || storedUuid.isEmpty) {
  17. storedUuid = _generateAndStoreUuid(prefs);
  18. }
  19. _cachedUuid = storedUuid;
  20. return storedUuid;
  21. }
  22. // 生成并存储新的 UUID
  23. static String _generateAndStoreUuid(SharedPreferences prefs) {
  24. final newUuid = const Uuid().v4();
  25. prefs.setString(_uuidKey, newUuid);
  26. return newUuid;
  27. }
  28. // 重置 UUID(用户选择重置隐私时使用)
  29. static Future<String> resetUuid() async {
  30. final prefs = await SharedPreferences.getInstance();
  31. _cachedUuid = null;
  32. return _generateAndStoreUuid(prefs);
  33. }
  34. // 检查是否已有 UUID
  35. static Future<bool> hasUuid() async {
  36. final prefs = await SharedPreferences.getInstance();
  37. return prefs.containsKey(_uuidKey);
  38. }
  39. // 清除 UUID(用户注销时)
  40. static Future<void> clearUuid() async {
  41. final prefs = await SharedPreferences.getInstance();
  42. await prefs.remove(_uuidKey);
  43. _cachedUuid = null;
  44. }
  45. }