一、封装代码
- 1、创建Preferences
- 2、获取Preferences实例
- 3、删除、put、get 等等
import dataPreferences from '@ohos.data.preferences';
import Constants from "../constant/Constant"
import Logger from "./Logger"
import GlobalContext from "./GlobalContext"
let preference: dataPreferences.Preferences;
let preferenceTemp: dataPreferences.Preferences;
let context = getContext(this);
export class PreferencesUtil {
/**
* Get the specified Preferences
* 第一种方式获取
* */
static async getPreferences(): Promise<dataPreferences.Preferences> {
return await GlobalContext.getContext().getObject(Constants.KEY_PREFERENCES) as dataPreferences.Preferences
}
/**
* Get the specified Preferences
* 第二种方式获取
* */
static getPreferencesOther(context: Context): Promise<dataPreferences.Preferences> {
return new Promise<dataPreferences.Preferences>((resolved,rejected) => {
dataPreferences.getPreferences(context, Constants.KEY_PREFERENCES)
.then((res) => {
resolved(res);
})
.catch(reason => {
rejected("hello,world");
})
});
}
/**
* Read the specified Preferences persistence file and load the data into the Preferences instance.
*/
static async createPreferences(context: Context) {
try {
preference = await dataPreferences.getPreferences(context, Constants.PREFERENCES_NAME);
GlobalContext.getContext().setObject(Constants.KEY_PREFERENCES, preference)
} catch (err) {
Logger.error(Constants.TAG, `Failed to get preferences, Cause: ${err}`);
}
}
/**
* Deletes the specified Preferences persistence file from memory and removes the Preferences instance.
*/
static async deletePreferences() {
try {
await dataPreferences.deletePreferences(context, Constants.PREFERENCES_NAME);
} catch (err) {
Logger.error(Constants.TAG, `Failed to delete preferences, Cause: ${err}`);
}
preference = preferenceTemp;
}
/**
* Save the data to the Preferences.
*
* @param data.
*/
static async put(key: string, value: unknown) {
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
if (typeof value === "number") {
await preference.put(key, value);
}
if (typeof value === "string") {
await preference.put(key, value);
}
if (typeof value === "boolean") {
await preference.put(key, value);
}
if (typeof value === "object") {
if (Array.isArray(value)) {
await preference.put(key, value);
} else {
await preference.put(key, JSON.stringify(value));
}
}
} catch (err) {
Logger.error("huxiubo", `Failed to put value, Cause: ${err}`);
}
// Store the Preference instance in the preference persistence file
await preference.flush();
}
/**
* Get preference data.
*/
static async get(key: string) {
let value: unknown;
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
value = await preference.get(key, undefined).then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
return value;
}
/**
* Get custom entity data.
*/
static async getEntity(key: string) {
let value: string = '';
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
value = (await preference.get(key, '')).toString();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
return JSON.parse(value);
}
/**
* Get an Object object that contains all key values.
*/
static async getAll() {
let value: unknown;
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
value = await preference.getAll().then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
return value;
}
/**
* Check if the Preferences instance contains a stored key value pair named the given Key
*/
static async has(key: string) {
let value: boolean = false;
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
value = await preference.has(key).then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
return value;
}
/**
* Delete a stored key value pair named the given Key from the Preferences instance
*/
static async delete(key: string) {
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
await preference.delete(key).then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
}
/**
* Clear all storage in this Preferences instance
*/
static async clear() {
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
await preference.clear().then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
}
/**
*Asynchronous storage of data from the current Preferences instance to the persistent file of user preferences
*/
static async flush() {
if (!preference) {
await this.createPreferences(getContext(this));
}
try {
await preference.flush().then();
} catch (err) {
Logger.error(Constants.TAG, `Failed to get value, Cause: ${err}`);
}
}
}
二、创建代码,在EntryAbility中的onWindowStageCreate
async onWindowStageCreate(windowStage: window.WindowStage) {
await PreferencesUtil.createPreferences(this.context)
PreferencesUtil.put("age", 10);
// put 值
PreferencesUtil.put("name", "huxiubo");
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
});
}
三、page中获取
import CommonConstants from '../common/constant/Constant'
import Logger from '../common/utils/Logger'
import { PreferencesUtil } from '../common/utils/PreferencesUtil'
import dataPreferences from '@ohos.data.preferences';
import UIAbility from '@ohos.app.ability.UIAbility';
import common from '@ohos.app.ability.common';
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
@State preference: dataPreferences.Preferences = null;
private context = getContext(this) as common.UIAbilityContext
async getPreference() {
try {
// 异步转同步使用
this.preference = await PreferencesUtil.getPreferences()
console.info(CommonConstants.TAG, `订阅首选项变化`);
this.preference.on('change',(data) => {
console.info(CommonConstants.TAG, `订阅 key : ${JSON.stringify(data)}`);
})
} catch (e) {
console.info(CommonConstants.TAG, `Failed : ${JSON.stringify(e)}`);
}
}
aboutToAppear() {
PreferencesUtil.get("age").then((value: number) => {
Logger.debug(CommonConstants.TAG, `get: ${value}`);
})
PreferencesUtil.get("name").then((value: string) => {
Logger.debug(CommonConstants.TAG, `get: ${value}`);
})
this.getPreference()
}
preferenceGet(): string {
let value = "";
PreferencesUtil.get("name").then((v: string) => {
value = v
Logger.debug(CommonConstants.TAG, `get: ${value}`);
})
return value
}
changeName() {
PreferencesUtil.put("name", "sulijing");
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.changeName()
})
}
.width('100%')
}
.height('100%')
}
}
其中可订阅数据变化
this.preference.on('change',(data) => {
console.info(CommonConstants.TAG, `订阅 key : ${JSON.stringify(data)}`);
})
四、GlobalContext
export default class GlobalContext {
private constructor() { }
private static instance: GlobalContext;
private _objects = new Map<string, Object>();
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
getObject(value: string): Object | undefined {
return this._objects.get(value);
}
setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
}
五、Logger
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import hilog from '@ohos.hilog';
const LOGGER_PREFIX: string = 'huxiubo';
class Logger {
private domain: number;
private prefix: string;
// format Indicates the log format string.
private format: string = '%{public}s, %{public}s';
/**
* constructor.
*
* @param prefix Identifies the log tag.
* @param domain Indicates the service domain, which is a hexadecimal integer ranging from 0x0 to 0xFFFFF
* @param args Indicates the log parameters.
*/
constructor(prefix: string = '', domain: number = 0xFF00) {
this.prefix = prefix;
this.domain = domain;
}
debug(...args: string[]): void {
hilog.debug(this.domain, this.prefix, this.format, args);
}
info(...args: string[]): void {
hilog.info(this.domain, this.prefix, this.format, args);
}
warn(...args: string[]): void {
hilog.warn(this.domain, this.prefix, this.format, args);
}
error(...args: string[]): void {
hilog.error(this.domain, this.prefix, this.format, args);
}
}
export default new Logger(LOGGER_PREFIX);
六 常量
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License,Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Style constants that can be used by all modules
*/
export default class Constants {
static readonly PREFERENCES_NAME: string = "zy";
static readonly TAG: string = "huxiubo";
static readonly KEY_PREFERENCES = "preferences"
}
👀关注公众号:Android老皮!!!欢迎大家来找我探讨交流👀