HarmonyOS实战开发:@ohos.data.preferences (用户首选项)

用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。

数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。

说明:

本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

import dataPreferences from '@ohos.data.preferences';复制到剪贴板错误复制

常量

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

名称参数类型可读可写说明
MAX_KEY_LENGTHKey的最大长度限制为80个字节。
MAX_VALUE_LENGTHValue的最大长度限制为8192个字节。

dataPreferences.getPreferences

getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void

获取Preferences实例,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
名字字符串Preferences实例的名称。
回调AsyncCallback<Preferences>回调函数。当获取Preferences实例成功,err为undefined,返回Preferences实例;否则err为错误对象。

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';

let context = featureAbility.getContext();
let preferences: dataPreferences.Preferences | null = null;

try {
    dataPreferences.getPreferences(context, 'myStore', (err: BusinessError, val: dataPreferences.Preferences) => {
        if (err) {
            console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        preferences = val;
        console.info("Succeeded in getting preferences.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: dataPreferences.Preferences) => {
                if (err) {
                console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
                return;
                }
                preferences = val;
                console.info("Succeeded in getting preferences.");
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}复制到剪贴板错误复制

dataPreferences.getPreferences

getPreferences(context: Context, name: string): Promise<Preferences>

获取Preferences实例,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
namestringPreferences实例的名称。

返回值:

类型说明
Promise<Preferences>Promise对象,返回Preferences实例。

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

let preferences: dataPreferences.Preferences | null = null;
try {
    let promise = dataPreferences.getPreferences(context, 'myStore');
    promise.then((object: dataPreferences.Preferences) => {
        preferences = object;
        console.info("Succeeded in getting preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let promise = dataPreferences.getPreferences(this.context, 'myStore');
            promise.then((object: dataPreferences.Preferences) => {
                preferences = object;
                console.info("Succeeded in getting preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.getPreferences10+

getPreferences(context: Context, options: Options, callback: AsyncCallback<Preferences>): void

获取Preferences实例,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
optionsOptions与Preferences实例相关的配置选项。
callbackAsyncCallback<Preferences>回调函数。当获取Preferences实例成功,err为undefined,返回Preferences实例;否则err为错误对象。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15501001Only supported in stage mode.
15501002The data group id is not valid.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();
let preferences: dataPreferences.Preferences | null = null;

try {
    let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
    dataPreferences.getPreferences(context, options, (err: BusinessError, val: dataPreferences.Preferences) => {
        if (err) {
            console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        preferences = val;
        console.info("Succeeded in getting preferences.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            dataPreferences.getPreferences(this.context, options, (err: BusinessError, val: dataPreferences.Preferences) => {
                if (err) {
                    console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                preferences = val;
                console.info("Succeeded in getting preferences.");
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.getPreferences10+

getPreferences(context: Context, options: Options): Promise<Preferences>

获取Preferences实例,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
optionsOptions与Preferences实例相关的配置选项。

返回值:

类型说明
Promise<Preferences>Promise对象,返回Preferences实例。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15501001Only supported in stage mode.
15501002The data group id is not valid.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();

let preferences: dataPreferences.Preferences | null = null;
try {
    let options: dataPreferences.Options =  { name: 'myStore' };
    let promise = dataPreferences.getPreferences(context, options);
    promise.then((object: dataPreferences.Preferences) => {
        preferences = object;
        console.info("Succeeded in getting preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options =  { name: 'myStore', dataGroupId:'myId' };
            let promise = dataPreferences.getPreferences(this.context, options);
            promise.then((object: dataPreferences.Preferences) => {
                preferences = object;
                console.info("Succeeded in getting preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.getPreferencesSync10+

getPreferencesSync(context: Context, options: Options): Preferences

获取Preferences实例,此为同步接口。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
optionsOptions与Preferences实例相关的配置选项。

返回值:

类型说明
Preferences返回Preferences实例。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15501001Only supported in stage mode.
15501002The data group id is not valid.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();
let preferences: dataPreferences.Preferences | null = null;

try {
    let options: dataPreferences.Options =  { name: 'myStore' };
    preferences = dataPreferences.getPreferencesSync(context, options);
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            preferences = dataPreferences.getPreferencesSync(this.context, options);
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to get preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.deletePreferences

deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void

从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用callback异步回调。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
namestringPreferences实例的名称。
callbackAsyncCallback<void>回调函数。当移除成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15500010Failed to delete preferences file.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

try {
    dataPreferences.deletePreferences(context, 'myStore', (err: BusinessError) => {
        if (err) {
            console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in deleting preferences." );
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            dataPreferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => {
                if (err) {
                    console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in deleting preferences." );
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to delete preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.deletePreferences

deletePreferences(context: Context, name: string): Promise<void>

从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用Promise异步回调。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
namestringPreferences实例的名称。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15500010Failed to delete preferences file.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

try {
    let promise = dataPreferences.deletePreferences(context, 'myStore');
    promise.then(() => {
        console.info("Succeeded in deleting preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try{
            let promise = dataPreferences.deletePreferences(this.context, 'myStore');
            promise.then(() => {
                console.info("Succeeded in deleting preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to delete preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.deletePreferences10+

deletePreferences(context: Context, options: Options, callback: AsyncCallback<void>): void

从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用callback异步回调。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
optionsOptions与Preferences实例相关的配置选项。
callbackAsyncCallback<void>回调函数。当移除成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15500010Failed to delete preferences file.
15501001Only supported in stage mode.
15501002The data group id is not valid.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

try {
    let options: dataPreferences.Options = { name: 'myStore' };
    dataPreferences.deletePreferences(context, options, (err: BusinessError) => {
        if (err) {
            console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in deleting preferences." );
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            dataPreferences.deletePreferences(this.context, options, (err: BusinessError) => {
                if (err) {
                    console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in deleting preferences." );
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to delete preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.deletePreferences10+

deletePreferences(context: Context, options: Options): Promise<void>

从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用Promise异步回调。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
选项Options与Preferences实例相关的配置选项。

返回值:

类型说明
承诺<无效>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15500010Failed to delete preferences file.
15501001Only supported in stage mode.
15501002The data group id is not valid.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();

try {
    let options: dataPreferences.Options = { name: 'myStore' };
    let promise = dataPreferences.deletePreferences(context, options);
    promise.then(() => {
        console.info("Succeeded in deleting preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete preferences. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try{
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            let promise = dataPreferences.deletePreferences(this.context, options);
            promise.then(() => {
                console.info("Succeeded in deleting preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to delete preferences. code =" + code + ", message =" + message);
        }
    }
}复制到剪贴板错误复制

dataPreferences.removePreferencesFromCache

removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void

从缓存中移出指定的Preferences实例,使用callback异步回调。

应用首次调用getPreferences接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次getPreferences时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
namestringPreferences实例的名称。
callbackAsyncCallback<void>回调函数。当移除成功,err为undefined,否则为错误对象。

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();
try {
    dataPreferences.removePreferencesFromCache(context, 'myStore', (err: BusinessError) => {
        if (err) {
            console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in removing preferences.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            dataPreferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => {
                if (err) {
                    console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in removing preferences.");
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.removePreferencesFromCache

removePreferencesFromCache(context: Context, name: string): Promise<void>

从缓存中移出指定的Preferences实例,使用Promise异步回调。

应用首次调用getPreferences接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次getPreferences时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
namestringPreferences实例的名称。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'

let context = featureAbility.getContext();
try {
    let promise = dataPreferences.removePreferencesFromCache(context, 'myStore');
    promise.then(() => {
        console.info("Succeeded in removing preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let promise = dataPreferences.removePreferencesFromCache(this.context, 'myStore');
            promise.then(() => {
                console.info("Succeeded in removing preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.removePreferencesFromCacheSync10+

removePreferencesFromCacheSync(context: Context, name: string): void

从缓存中移出指定的Preferences实例,此为同步接口。

应用首次调用getPreferences接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次getPreferences时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
namestringPreferences实例的名称。

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();
try {
    dataPreferences.removePreferencesFromCacheSync(context, 'myStore');
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            dataPreferences.removePreferencesFromCacheSync(this.context, 'myStore');
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}复制到剪贴板错误复制

dataPreferences.removePreferencesFromCache10+

removePreferencesFromCache(context: Context, options: Options, callback: AsyncCallback<void>): void

从缓存中移出指定的Preferences实例,使用callback异步回调。

应用首次调用getPreferences接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次getPreferences时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
选项Options与Preferences实例相关的配置选项。
回调AsyncCallback<void>回调函数。当移除成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15501001Only supported in stage mode.
15501002The data group id is not valid.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();
try {
    let options: dataPreferences.Options = { name: 'myStore' };
    dataPreferences.removePreferencesFromCache(context, options, (err: BusinessError) => {
        if (err) {
            console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in removing preferences.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            dataPreferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => {
                if (err) {
                    console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
                    return;
                }
                console.info("Succeeded in removing preferences.");
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}复制到剪贴板错误复制

dataPreferences.removePreferencesFromCache10+

removePreferencesFromCache(context: Context, options: Options): Promise<void>

从缓存中移出指定的Preferences实例,使用Promise异步回调。

应用首次调用getPreferences接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次getPreferences时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
optionsOptions与Preferences实例相关的配置选项。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15501001Only supported in stage mode.
15501002The data group id is not valid.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base'
let context = featureAbility.getContext();
try {
    let options: dataPreferences.Options = { name: 'myStore' };
    let promise = dataPreferences.removePreferencesFromCache(context, options);
    promise.then(() => {
        console.info("Succeeded in removing preferences.");
    }).catch((err: BusinessError) => {
        console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base'
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            let promise = dataPreferences.removePreferencesFromCache(this.context, options);
            promise.then(() => {
                console.info("Succeeded in removing preferences.");
            }).catch((err: BusinessError) => {
                console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
            })
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}Copy to clipboardErrorCopied

dataPreferences.removePreferencesFromCacheSync10+

removePreferencesFromCacheSync(context: Context, options: Options):void

从缓存中移出指定的Preferences实例,此为同步接口。

应用首次调用getPreferences接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次getPreferences时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。

调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
contextContext应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
optionsOptions与Preferences实例相关的配置选项。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15501001Only supported in stage mode.
15501002The data group id is not valid.

示例:

FA模型示例:

// 获取context
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
    let options: dataPreferences.Options = { name: 'myStore' };
    dataPreferences.removePreferencesFromCacheSync(context, options);
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to remove preferences. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

Stage模型示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';

class EntryAbility extends UIAbility {
    onWindowStageCreate(windowStage: window.WindowStage) {
        try {
            let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
            dataPreferences.removePreferencesFromCacheSync(this.context, options);
        } catch (err) {
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error("Failed to remove preferences. code =" + code + ", message =" + message);
        }
    }
}复制到剪贴板错误复制

Options10+

Preferences实例配置选项。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

名称类型必填说明
名字字符串Preferences实例的名称。
dataGroupId字符串应用组ID,需要向应用市场获取。
模型约束: 此属性仅在Stage模型下可用。
从API version 10开始,支持此可选参数。指定在此dataGroupId对应的沙箱路径下创建Preferences实例,当此参数不填时,默认在本应用沙箱目录下创建Preferences实例。

Preferences

首选项实例,提供获取和修改存储数据的接口。

下列接口都需先使用dataPreferences.getPreferences获取到Preferences实例,再通过此实例调用对应接口。

get

get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void

从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
key字符串要获取的存储Key名称,不能为空。
defValueValueType默认返回值。支持number、string、boolean、Array<number>、Array<string>、Array<boolean>类型。
回调AsyncCallback<ValueType>回调函数。当获取成功时,err为undefined,data为键对应的值;否则err为错误对象。

示例:

try {
    preferences.get('startup', 'default', (err: BusinessError, val: dataPreferences.ValueType) => {
        if (err) {
            console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in getting value of 'startup'. val: " + val);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

get

get(key: string, defValue: ValueType): Promise<ValueType>

从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
keystring要获取的存储Key名称,不能为空。
defValueValueType默认返回值。支持number、string、boolean、Array<number>、Array<string>、Array<boolean>类型。

返回值:

类型说明
Promise<ValueType>Promise对象,返回键对应的值。

示例:

try {
    let promise = preferences.get('startup', 'default');
    promise.then((data: dataPreferences.ValueType) => {
        console.info("Succeeded in getting value of 'startup'. Data: " + data);
    }).catch((err: BusinessError) => {
        console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

getSync10+

getSync(key: string, defValue: ValueType): ValueType

从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,此为同步接口。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
keystring要获取的存储Key名称,不能为空。
defValueValueType默认返回值。支持number、string、boolean、Array<number>、Array<string>、Array<boolean>类型。

返回值:

类型说明
ValueType返回键对应的值。

示例:

try {
    let value: dataPreferences.ValueType = preferences.getSync('startup', 'default');
    console.info("Succeeded in getting value of 'startup'. Data: " + value);
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

getAll

getAll(callback: AsyncCallback<Object>): void;

从缓存的Preferences实例中获取所有键值数据。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
callbackAsyncCallback<Object>回调函数。当获取成功,err为undefined,value为所有键值数据;否则err为错误对象。

示例:

// 由于ArkTS中无Object.keys,且无法使用for..in...
// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用
function getObjKeys(obj: Object): string[] {
  let keys = Object.keys(obj);
  return keys;
}

try {
    preferences.getAll((err: BusinessError, value: Object) => {
        if (err) {
            console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
            return;
        }
        let allKeys = getObjKeys(value);
        console.info("getAll keys = " + allKeys);
        console.info("getAll object = " + JSON.stringify(value));
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get all key-values. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

getAll

getAll(): Promise<Object>

从缓存的Preferences实例中获取所有键值数据。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

返回值:

类型说明
Promise<Object>Promise对象,返回含有所有键值数据。

示例:

// 由于ArkTS中无Object.keys,且无法使用for..in...
// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用
function getObjKeys(obj: Object): string[] {
  let keys = Object.keys(obj);
  return keys;
}

try {
    let promise = preferences.getAll();
    promise.then((value: Object) => {
        let allKeys = getObjKeys(value);
        console.info('getAll keys = ' + allKeys);
        console.info("getAll object = " + JSON.stringify(value));
    }).catch((err: BusinessError) => {
        console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get all key-values. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

getAllSync10+

getAllSync(): Object

从缓存的Preferences实例中获取所有键值数据,此为同步接口。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

返回值:

类型说明
Object返回含有所有键值数据。

示例:

// 由于ArkTS中无Object.keys,且无法使用for..in...
// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用
function getObjKeys(obj: Object): string[] {
  let keys = Object.keys(obj);
  return keys;
}

try {
    let value = preferences.getAllSync();
    let allKeys = getObjKeys(value);
    console.info('getAll keys = ' + allKeys);
    console.info("getAll object = " + JSON.stringify(value));
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to get all key-values. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

put

put(key: string, value: ValueType, callback: AsyncCallback<void>): void

将数据写入缓存的Preferences实例中,可通过flush将Preferences实例持久化,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
key字符串要修改的存储的Key,不能为空。
价值ValueType存储的新值。支持number、string、boolean、Array<number>、Array<string>、Array<boolean>类型。
回调AsyncCallback<void>回调函数。当数据写入成功,err为undefined;否则为错误对象。

示例:

try {
    preferences.put('startup', 'auto', (err: BusinessError) => {
        if (err) {
            console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in putting value of 'startup'.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to put value of 'startup'. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

put

put(key: string, value: ValueType): Promise<void>

将数据写入缓存的Preferences实例中,可通过flush将Preferences实例持久化,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
keystring要修改的存储的Key,不能为空。
valueValueType存储的新值。支持number、string、boolean、Array<number>、Array<string>、Array<boolean>类型。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

示例:

try {
    let promise = preferences.put('startup', 'auto');
    promise.then(() => {
        console.info("Succeeded in putting value of 'startup'.");
    }).catch((err: BusinessError) => {
        console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to put value of 'startup'. code =" + code +", message =" + message);
}Copy to clipboardErrorCopied

putSync10+

putSync(key: string, value: ValueType): void

将数据写入缓存的Preferences实例中,可通过flush将Preferences实例持久化,此为同步接口。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
keystring要修改的存储的Key,不能为空。
valueValueType存储的新值。支持number、string、boolean、Array<number>、Array<string>、Array<boolean>类型。

示例:

try {
    preferences.putSync('startup', 'auto');
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to put value of 'startup'. code =" + code +", message =" + message);
}Copy to clipboardErrorCopied

has

has(key: string, callback: AsyncCallback<boolean>): void

检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
key字符串要检查的存储key名称,不能为空。
回调AsyncCallback<boolean>回调函数。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。

示例:

try {
    preferences.has('startup', (err: BusinessError, val: boolean) => {
        if (err) {
            console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
            return;
        }
        if (val) {
            console.info("The key 'startup' is contained.");
        } else {
            console.info("The key 'startup' dose not contain.");
        }
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

has

has(key: string): Promise<boolean>

检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
key字符串要检查的存储key名称,不能为空。

返回值:

类型说明
Promise<boolean>Promise对象。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。

示例:

try {
    let promise = preferences.has('startup');
    promise.then((val: boolean) => {
        if (val) {
            console.info("The key 'startup' is contained.");
        } else {
            console.info("The key 'startup' dose not contain.");
        }
    }).catch((err: BusinessError) => {
        console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

hasSync10+

hasSync(key: string): boolean

检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,此为同步接口。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
key字符串要检查的存储key名称,不能为空。

返回值:

类型说明
boolean返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。

示例:

try {
    let isExist: boolean = preferences.hasSync('startup');
    if (isExist) {
        console.info("The key 'startup' is contained.");
    } else {
        console.info("The key 'startup' dose not contain.");
    }
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

delete

delete(key: string, callback: AsyncCallback<void>): void

从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过flush将Preferences实例持久化,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
keystring要删除的存储Key名称,不能为空。
callbackAsyncCallback<void>回调函数。当删除成功,err为undefined;否则为错误对象。

示例:

try {
    preferences.delete('startup', (err: BusinessError) => {
        if (err) {
            console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in deleting the key 'startup'.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete the key 'startup'. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

delete

delete(key: string): Promise<void>

从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过flush将Preferences实例持久化,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
keystring要删除的存储key名称,不能为空。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

示例:

try {
    let promise = preferences.delete('startup');
    promise.then(() => {
        console.info("Succeeded in deleting the key 'startup'.");
    }).catch((err: BusinessError) => {
        console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message);
}Copy to clipboardErrorCopied

deleteSync10+

deleteSync(key: string): void

从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过flush将Preferences实例持久化,此为同步接口。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
keystring要删除的存储key名称,不能为空。

示例:

try {
    preferences.deleteSync('startup');
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message);
}Copy to clipboardErrorCopied

flush

flush(callback: AsyncCallback<void>): void

将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。当保存成功,err为undefined;否则为错误对象。

示例:

try {
    preferences.flush((err: BusinessError) => {
        if (err) {
            console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in flushing.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to flush. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

flush

flush(): Promise<void>

将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

示例:

try {
    let promise = preferences.flush();
    promise.then(() => {
        console.info("Succeeded in flushing.");
    }).catch((err: BusinessError) => {
        console.error("Failed to flush. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to flush. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

clear

clear(callback: AsyncCallback<void>): void

清除缓存的Preferences实例中的所有数据,可通过flush将Preferences实例持久化,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
回调AsyncCallback<void>回调函数。当清除成功,err为undefined;否则为错误对象。

示例:

try {
    preferences.clear((err: BusinessError) =>{
        if (err) {
            console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
            return;
        }
        console.info("Succeeded in clearing.");
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to clear. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

clear

clear(): Promise<void>

清除缓存的Preferences实例中的所有数据,可通过flush将Preferences实例持久化,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

返回值:

类型说明
承诺<无效>无返回结果的Promise对象。

示例:

try {
    let promise = preferences.clear();
    promise.then(() => {
        console.info("Succeeded in clearing.");
    }).catch((err: BusinessError) => {
        console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to clear. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

clearSync10+

clearSync(): void

清除缓存的Preferences实例中的所有数据,可通过flush将Preferences实例持久化,此为同步接口。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

示例:

try {
    preferences.clearSync();
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to clear. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

on('change')

on(type: 'change', callback: ( key : string ) => void): void

订阅数据变更,订阅的Key的值发生变更后,在执行flush方法后,触发callback回调。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
typestring事件类型,固定值'change',表示数据变更。
callbackFunction回调函数。
key: 发生变化的Key。

示例:

try {
    dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
        if (err) {
            console.error("Failed to get preferences.");
            return;
        }
        preferences.on('change', (key: string) => {
            console.info("The key " + key + " changed.");
        });
        preferences.put('startup', 'manual', (err: BusinessError) => {
            if (err) {
            console.error("Failed to put the value of 'startup'. Cause: " + err);
            return;
            }
            console.info("Succeeded in putting the value of 'startup'.");

            preferences.flush((err: BusinessError) => {
            if (err) {
                console.error("Failed to flush. Cause: " + err);
                return;
            }
            console.info("Succeeded in flushing.");
            })
        })
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to flush. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

on('multiProcessChange')10+

on(type: 'multiProcessChange', callback: ( key : string ) => void): void

订阅进程间数据变更,多个进程持有同一个首选项文件时,订阅的Key的值在任意一个进程发生变更后,执行flush方法后,触发callback回调。

此方法可以配合removePreferencesFromCache使用,当监听到有进程更新了文件时,在回调方法中更新当前的Preferences实例,如下示例2。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
typestring事件类型,固定值'multiProcessChange',表示多进程间的数据变更。
callbackFunction回调函数。
key: 发生变化的Key。

错误码:

以下错误码的详细介绍请参见用户首选项错误码

错误码ID错误信息
15500019Failed to obtain subscription service.

示例1:

try {
    let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
    dataPreferences.getPreferences(this.context, options, (err: BusinessError, preferences: dataPreferences.Preferences) => {
        if (err) {
            console.error("Failed to get preferences.");
            return;
        }
        preferences.on('multiProcessChange', (key: string) => {
            console.info("The key " + key + " changed.");
        });
        preferences.put('startup', 'manual', (err: BusinessError) => {
            if (err) {
                console.error("Failed to put the value of 'startup'. Cause: " + err);
                return;
            }
            console.info("Succeeded in putting the value of 'startup'.");
            preferences.flush((err: BusinessError) => {
                if (err) {
                    console.error("Failed to flush. Cause: " + err);
                    return;
                }
                console.info("Succeeded in flushing.");
            })
        })
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to flush. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

示例2:

try {
    let options: dataPreferences.Options = { name: 'myStore' };
    dataPreferences.getPreferences(this.context, options, (err: BusinessError, val: dataPreferences.Preferences) => {
        if (err) {
            console.error("Failed to get preferences.");
            return;
        }
        preferences = val;
        preferences.on('multiProcessChange', (key: string) => {
            console.info("The key " + key + " changed.");
            try {
                dataPreferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => {
                    if (err) {
                        console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
                        return;
                    }
                    preferences = null;
                    console.info("Succeeded in removing preferences.");
                })
            } catch (err) {
                let code = (err as BusinessError).code;
                let message = (err as BusinessError).message;
                console.error("Failed to remove preferences. code =" + code + ", message =" + message);
            }

            try {
                dataPreferences.getPreferences(this.context, options, (err: BusinessError, val: dataPreferences.Preferences) => {
                    if (err) {
                        console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message);
                        return;
                    }
                    preferences = val;
                    console.info("Succeeded in getting preferences.");
                })
            } catch (err) {
                let code = (err as BusinessError).code;
                let message = (err as BusinessError).message;
                console.error("Failed to get preferences. code =" + code + ", message =" + message);
            }
        });
        preferences.put('startup', 'manual', (err: BusinessError) => {
            if (err) {
                console.error("Failed to put the value of 'startup'. Cause: " + err);
                return;
            }
            console.info("Succeeded in putting the value of 'startup'.");

            if (preferences != null) {
                preferences.flush((err: BusinessError) => {
                    if (err) {
                        console.error("Failed to flush. Cause: " + err);
                        return;
                    }
                    console.info("Succeeded in flushing.");
                })
            }
        })
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to flush. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

off('change')

off(type: 'change', callback?: ( key : string ) => void): void

取消订阅数据变更。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
类型字符串事件类型,固定值'change',表示数据变更。
回调Function需要取消的回调函数,不填写则全部取消。
key: 发生变化的Key。

示例:


try {
    dataPreferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: dataPreferences.Preferences) => {
        if (err) {
            console.error("Failed to get preferences.");
            return;
        }
        preferences.on('change', (key: string) => {
            console.info("The key " + key + " changed.");
        });
        preferences.put('startup', 'auto', (err: BusinessError) => {
            if (err) {
                console.error("Failed to put the value of 'startup'. Cause: " + err);
                return;
            }
            console.info("Succeeded in putting the value of 'startup'.");

            preferences.flush((err: BusinessError) =>{
                if (err) {
                    console.error("Failed to flush. Cause: " + err);
                    return;
                }
                console.info("Succeeded in flushing.");
            })
            preferences.off('change', (key: string) => {
                console.info("The key " + key + " changed.");
            });
        })
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to flush. code =" + code + ", message =" + message);
}复制到剪贴板错误复制

off('multiProcessChange')10+

off(type: 'multiProcessChange', callback?: ( key : string ) => void): void

取消订阅进程间数据变更。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

参数:

参数名类型必填说明
typestring事件类型,固定值'multiProcessChange',表示多进程间的数据变更。
callbackFunction需要取消的回调函数,不填写则全部取消。
key: 发生变化的Key。

示例:

try {
    let options: dataPreferences.Options = { name: 'myStore', dataGroupId:'myId' };
    dataPreferences.getPreferences(this.context, options, (err: BusinessError, preferences: dataPreferences.Preferences) => {
        if (err) {
            console.error("Failed to get preferences.");
            return;
        }
        preferences.on('multiProcessChange', (key: string) => {
            console.info("The key " + key + " changed.");
        });
        preferences.put('startup', 'auto', (err: BusinessError) => {
            if (err) {
                console.error("Failed to put the value of 'startup'. Cause: " + err);
                return;
            }
            console.info("Succeeded in putting the value of 'startup'.");

            preferences.flush((err: BusinessError) => {
                if (err) {
                    console.error("Failed to flush. Cause: " + err);
                    return;
                }
                console.info("Succeeded in flushing.");
            })
            preferences.off('multiProcessChange', (key: string) => {
                console.info("The key " + key + " changed.");
            });
        })
    })
} catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message;
    console.error("Failed to flush. code =" + code + ", message =" + message);
}Copy to clipboardErrorCopied

ValueType

用于表示允许的数据字段类型。

系统能力: SystemCapability.DistributedDataManager.Preferences.Core

类型说明
表示值类型为数字。
字符串表示值类型为字符串。
布尔表示值类型为布尔值。
Array<number>表示值类型为数字类型的数组。
Array<boolean>表示值类型为布尔类型的数组。
数组<字符串>表示值类型为字符串类型的数组。

最后

有很多小伙伴不知道学习哪些鸿蒙开发技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?而且学习时频繁踩坑,最终浪费大量时间。所以有一份实用的鸿蒙(HarmonyOS NEXT)资料用来跟着学习是非常有必要的。 

这份鸿蒙(HarmonyOS NEXT)资料包含了鸿蒙开发必掌握的核心知识要点,内容包含了ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(HarmonyOS NEXT)技术知识点。

希望这一份鸿蒙学习资料能够给大家带来帮助,有需要的小伙伴自行领取,限时开源,先到先得~无套路领取!!

获取这份完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

鸿蒙(HarmonyOS NEXT)最新学习路线

  •  HarmonOS基础技能

  • HarmonOS就业必备技能 
  •  HarmonOS多媒体技术

  • 鸿蒙NaPi组件进阶

  • HarmonOS高级技能

  • 初识HarmonOS内核 
  • 实战就业级设备开发

有了路线图,怎么能没有学习资料呢,小编也准备了一份联合鸿蒙官方发布笔记整理收纳的一套系统性的鸿蒙(OpenHarmony )学习手册(共计1236页)鸿蒙(OpenHarmony )开发入门教学视频,内容包含:ArkTS、ArkUI、Web开发、应用模型、资源分类…等知识点。

获取以上完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

《鸿蒙 (OpenHarmony)开发入门教学视频》

《鸿蒙生态应用开发V2.0白皮书》

图片

《鸿蒙 (OpenHarmony)开发基础到实战手册》

OpenHarmony北向、南向开发环境搭建

图片

 《鸿蒙开发基础》

  • ArkTS语言
  • 安装DevEco Studio
  • 运用你的第一个ArkTS应用
  • ArkUI声明式UI开发
  • .……

图片

 《鸿蒙开发进阶》

  • Stage模型入门
  • 网络管理
  • 数据管理
  • 电话服务
  • 分布式应用开发
  • 通知与窗口管理
  • 多媒体技术
  • 安全技能
  • 任务管理
  • WebGL
  • 国际化开发
  • 应用测试
  • DFX面向未来设计
  • 鸿蒙系统移植和裁剪定制
  • ……

图片

《鸿蒙进阶实战》

  • ArkTS实践
  • UIAbility应用
  • 网络案例
  • ……

图片

 获取以上完整鸿蒙HarmonyOS学习资料,请点击→纯血版全套鸿蒙HarmonyOS学习资料

总结

总的来说,华为鸿蒙不再兼容安卓,对中年程序员来说是一个挑战,也是一个机会。只有积极应对变化,不断学习和提升自己,他们才能在这个变革的时代中立于不败之地。

  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值