设备号

This commit is contained in:
chen wei bo
2025-08-15 16:19:31 +08:00
parent 599c98f135
commit 9debc1238d
10 changed files with 129 additions and 0 deletions
@@ -0,0 +1,41 @@
import KVStore from "../storage/KVStore";
import DeviceId from "./DeviceId";
export class DeviceIdService {
private static _I: DeviceIdService | null = null;
static get I(): DeviceIdService { return this._I ?? (this._I = new DeviceIdService()); }
private constructor(private store = new KVStore("app:")) {}
private static KEY = "device_id";
private _id: string | null = null;
private _inited = false;
/** 启动时调用:加载或生成并持久化 */
init(): void {
if (this._inited) return;
const saved = this.store.get(DeviceIdService.KEY);
if (saved) {
this._id = saved;
} else {
// 如需原生ID,可先尝试原生,再用 UUID 兜底
this._id = DeviceId.uuidv4();
this.store.set(DeviceIdService.KEY, this._id);
}
this._inited = true;
}
/** 获取设备号(若未 init,会懒初始化一次) */
get id(): string {
if (!this._inited) this.init();
// 理论上不为空,保险起见再兜底
return this._id ?? DeviceId.uuidv4();
}
/** 重置(合规/调试用) */
reset(): void {
this.store.remove(DeviceIdService.KEY);
this._id = null;
this._inited = false;
}
}
export default DeviceIdService;