@ohos.data.preferences (用户首选项)

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

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

说明:

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

导入模块

import dataPreferences from '@ohos.data.preferences';

常量

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

名称 参数类型 可读 可写 说明
MAX_KEY_LENGTH number Key的最大长度限制为80个字节。
MAX_VALUE_LENGTH number Value的最大长度限制为8192个字节。

dataPreferences.getPreferences

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

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

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

参数:

参数名 类型 必填 说明
context Context 应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
name string Preferences实例的名称。
callback 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

参数:

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

返回值:

类型 说明
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);
}

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);
        }
    }
}

dataPreferences.getPreferences10+

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

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

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

参数:

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

错误码:

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

错误码ID 错误信息
15501001 Only supported in stage mode.
15501002 The 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' };
    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);
}

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);
        }
    }
}

dataPreferences.getPreferences10+

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

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

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

参数:

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

返回值:

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

错误码:

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

错误码ID 错误信息
15501001 Only supported in stage mode.
15501002 The 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);
}

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);
        }
    }
}

dataPreferences.getPreferencesSync10+

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

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

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

参数:

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

返回值:

类型 说明
Preferences 返回Preferences实例。

错误码:

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

错误码ID 错误信息
15501001 Only supported in stage mode.
15501002 The 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);
}

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);
        }
    }
}

dataPreferences.deletePreferences

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

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

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

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

参数:

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

错误码:

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

错误码ID 错误信息
15500010 Failed 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);
}

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);
        }
    }
}

dataPreferences.deletePreferences

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

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

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

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

参数:

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

返回值:

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

错误码:

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

错误码ID 错误信息
15500010 Failed 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);
}

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);
        }
    }
}

dataPreferences.deletePreferences10+

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

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

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

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

参数:

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

错误码:

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

错误码ID 错误信息
15500010 Failed to delete preferences file.
15501001 Only supported in stage mode.
15501002 The 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);
}

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);
        }
    }
}

dataPreferences.deletePreferences10+

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

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

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

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

参数:

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

返回值:

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

错误码:

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

错误码ID 错误信息
15500010 Failed to delete preferences file.
15501001 Only supported in stage mode.
15501002 The 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

参数:

参数名 类型 必填 说明
context Context 应用上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
name string Preferences实例的名称。
callback AsyncCallback<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);
}

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);
        }
    }
}

dataPreferences.removePreferencesFromCache

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

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

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

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

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

参数:

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

返回值:

类型 说明
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);
}

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);
        }
    }
}

dataPreferences.removePreferencesFromCacheSync10+

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

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

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

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

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

参数:

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

示例:

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);
}

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

参数:

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

错误码:

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

错误码ID 错误信息
15501001 Only supported in stage mode.
15501002 The 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

参数:

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

返回值:

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

错误码:

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

错误码ID 错误信息
15501001 Only supported in stage mode.
15501002 The 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);
}

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);
        }
    }
}

dataPreferences.removePreferencesFromCacheSync10+

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

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

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

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

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

参数:

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

错误码:

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

错误码ID 错误信息
15501001 Only supported in stage mode.
15501002 The 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);
}

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

名称 类型 必填 说明
name string Preferences实例的名称。
dataGroupId string 应用组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 string 要获取的存储Key名称,不能为空。
defValue ValueType 默认返回值。支持number、string、boolean、Array<number>、Array<string>、Array<boolean>类型。
callback AsyncCallback<ValueType> 回调函数。当获取成功时,err为undefined,data为键对应的值;否则err为错误对象。

示例:

import {BusinessError} from '@ohos.base';

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

参数:

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

返回值:

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

示例:

import {BusinessError} from '@ohos.base';

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);
}

getSync10+

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

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

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

参数:

参数名 类型 必填 说明
key string 要获取的存储Key名称,不能为空。
defValue ValueType 默认返回值。支持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);
}

getAll

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

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

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

参数:

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

示例:

import {BusinessError} from '@ohos.base';

// 由于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);
}

getAll

getAll(): Promise<Object>

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

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

返回值:

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

示例:

import {BusinessError} from '@ohos.base';

// 由于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);
}

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异步回调。

说明:

当对应的键已经存在时,put()方法会覆盖其值。可以使用hasSync()方法检查是否存在对应键值对。

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

参数:

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

示例:

import {BusinessError} from '@ohos.base';

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异步回调。

说明:

当对应的键已经存在时,put()方法会覆盖其值。可以使用hasSync()方法检查是否存在对应键值对。

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

参数:

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

返回值:

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

示例:

import {BusinessError} from '@ohos.base';

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);
}

putSync10+

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

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

说明:

当对应的键已经存在时,putSync()方法会覆盖其值。可以使用hasSync()方法检查是否存在对应键值对。

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

参数:

参数名 类型 必填 说明
key string 要修改的存储的Key,不能为空。
value ValueType 存储的新值。支持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);
}

has

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

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

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

参数:

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

示例:

import {BusinessError} from '@ohos.base';

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 string 要检查的存储key名称,不能为空。

返回值:

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

示例:

import {BusinessError} from '@ohos.base';

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 string 要检查的存储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);
}

delete

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

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

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

参数:

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

示例:

import {BusinessError} from '@ohos.base';

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);
}

delete

delete(key: string): Promise<void>

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

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

参数:

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

返回值:

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

示例:

import {BusinessError} from '@ohos.base';

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);
}

deleteSync10+

deleteSync(key: string): void

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

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

参数:

参数名 类型 必填 说明
key string 要删除的存储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);
}

flush

flush(callback: AsyncCallback<void>): void

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

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

参数:

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

示例:

import {BusinessError} from '@ohos.base';

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);
}

flush

flush(): Promise<void>

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

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

返回值:

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

示例:

import {BusinessError} from '@ohos.base';

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);
}

clear

clear(callback: AsyncCallback<void>): void

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

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

参数:

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

示例:

import {BusinessError} from '@ohos.base';

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<void> 无返回结果的Promise对象。

示例:

import {BusinessError} from '@ohos.base';

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

参数:

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

示例:

import {BusinessError} from '@ohos.base';

let observer = (key: string) => {
  console.info("The key " + key + " changed.");
}
preferences.on('change', observer);
preferences.putSync('startup', 'manual');
preferences.flush((err: BusinessError) => {
  if (err) {
    console.error("Failed to flush. Cause: " + err);
    return;
  }
  console.info("Succeeded in flushing.");
})

on('multiProcessChange')10+

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

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

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

参数:

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

错误码:

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

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

示例:

import {BusinessError} from '@ohos.base';

let observer = (key: string) => {
  console.info("The key " + key + " changed.");
}
preferences.on('multiProcessChange', observer);
preferences.putSync('startup', 'manual');
preferences.flush((err: BusinessError) => {
  if (err) {
    console.error("Failed to flush. Cause: " + err);
    return;
  }
  console.info("Succeeded in flushing.");
})

off('change')

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

取消订阅数据变更。

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

参数:

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

示例:

import {BusinessError} from '@ohos.base';

let observer = (key: string) => {
  console.info("The key " + key + " changed.");
}
preferences.on('change', observer);
preferences.putSync('startup', 'auto');
preferences.flush((err: BusinessError) => {
  if (err) {
    console.error("Failed to flush. Cause: " + err);
    return;
  }
  console.info("Succeeded in flushing.");
})
preferences.off('change', observer);

off('multiProcessChange')10+

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

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

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

参数:

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

示例:

import {BusinessError} from '@ohos.base';

let observer = (key: string) => {
  console.info("The key " + key + " changed.");
}
preferences.on('multiProcessChange', observer);
preferences.putSync('startup', 'auto');
preferences.flush((err: BusinessError) => {
  if (err) {
    console.error("Failed to flush. Cause: " + err);
    return;
  }
  console.info("Succeeded in flushing.");
})
preferences.off('multiProcessChange', observer);

ValueType

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

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

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