-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBaseLocalStorage.ets
65 lines (55 loc) · 1.91 KB
/
BaseLocalStorage.ets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { Context } from '@kit.AbilityKit';
import dataPreferences from '@ohos.data.preferences';
import { Log } from './Log';
export class BaseLocalStorageKey {
static readonly KEY_SERVER_CONFIG = "key_config";
}
export class BaseLocalStorage {
private static instance: BaseLocalStorage;
private static lock: boolean = false;
private static readonly XY_DP_Name = "LocalData";
static getInstance(): BaseLocalStorage {
if (!BaseLocalStorage.instance) {
if (!BaseLocalStorage.lock) {
BaseLocalStorage.lock = true;
BaseLocalStorage.instance = new BaseLocalStorage();
BaseLocalStorage.lock = false;
}
}
return BaseLocalStorage.instance;
}
private context: Context | null = null;
private preferences: dataPreferences.Preferences | null = null;
private constructor() {
}
public init(context: Context): void {
if (!this.context) {
this.context = context.getApplicationContext();
let options: dataPreferences.Options = { name: BaseLocalStorage.XY_DP_Name };
this.preferences = dataPreferences.getPreferencesSync(this.context, options);
} else {
Log.info("LocalStorage is already init.")
}
}
public putData(key: string, value: dataPreferences.ValueType) {
Log.info(`put sp data, key:${key}, value:${value}`)
this.preferences?.putSync(key, value);
this.preferences?.flush();
}
public clearData(key: string) {
this.preferences?.delete(key);
this.preferences?.flush();
}
public getData(key: string, defaultValue: dataPreferences.ValueType): dataPreferences.ValueType | undefined {
let value = this.preferences?.getSync(key, defaultValue);
Log.info(`get sp data, key:${key}, value:${value}`)
return value;
}
public getObject<T>(key: string): T {
let value = this.getData(key, "{}") as string;
if (value.toString().length > 0) {
return JSON.parse(value) as T;
}
return "{}" as T;
}
}