feat: enhance device ID generation with timeout and refactor shared_preferences dependency for OHOS compatibility
This commit is contained in:
@@ -15,15 +15,34 @@ import 'package:core_storage/core_storage.dart';
|
||||
/// 这里的语义是"这次安装":卸载重装换一个新 ID 是**预期行为**,不需要跨安装
|
||||
/// 追踪——它的用途只有一个,把同一台设备的日志串起来排查问题。
|
||||
/// ---------------------------------------------------------------------------
|
||||
Future<String> loadOrCreateDeviceId(Prefs prefs) async {
|
||||
Future<String> loadOrCreateDeviceId(
|
||||
Prefs prefs, {
|
||||
Duration timeout = const Duration(seconds: 2),
|
||||
}) async {
|
||||
const String key = 'device_id';
|
||||
|
||||
try {
|
||||
return await _loadOrCreatePersistedDeviceId(prefs, key).timeout(timeout);
|
||||
} on Object {
|
||||
// 本地存储只增强日志关联,不能因未注册的平台插件阻断 runApp()。
|
||||
// 当前值仅在本次进程有效;下次启动仍会尝试读写持久化 ID。
|
||||
return _newDeviceId();
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> _loadOrCreatePersistedDeviceId(Prefs prefs, String key) async {
|
||||
final String? existing = await prefs.getString(key);
|
||||
if (existing != null && existing.isNotEmpty) {
|
||||
return existing;
|
||||
}
|
||||
final Random random = Random.secure();
|
||||
final List<int> bytes = List<int>.generate(16, (int _) => random.nextInt(256));
|
||||
final String created = base64Url.encode(bytes).replaceAll('=', '');
|
||||
|
||||
final String created = _newDeviceId();
|
||||
await prefs.setString(key, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
String _newDeviceId() {
|
||||
final Random random = Random.secure();
|
||||
final List<int> bytes = List<int>.generate(16, (int _) => random.nextInt(256));
|
||||
return base64Url.encode(bytes).replaceAll('=', '');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user