@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模型示例:

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

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

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

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) {
    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.");
    })
  }
}

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

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

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;

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

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) {
    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.");
    })
  }
}

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

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

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';

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

let options: dataPreferences.Options = { name: 'myStore' };
preferences = dataPreferences.getPreferencesSync(context, options);

Stage模型示例:

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

let preferences: dataPreferences.Preferences | null = null;

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage) {
    let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' };
    preferences = dataPreferences.getPreferencesSync(this.context, options);
  }
}

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

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

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) {
    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.");
    })
  }
}

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

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

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

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

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

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) {
    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.");
    })
  }
}

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

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

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

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();
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.");
})

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) {
    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.");
    })
  }
}

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

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

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';
let context = featureAbility.getContext();
dataPreferences.removePreferencesFromCacheSync(context, 'myStore');

Stage模型示例:

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

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage) {
    dataPreferences.removePreferencesFromCacheSync(this.context, 'myStore');
  }
}

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();
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.");
})

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) {
    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.");
    })
  }
}

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

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

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();
let options: dataPreferences.Options = { name: 'myStore' };
dataPreferences.removePreferencesFromCacheSync(context, options);

Stage模型示例:

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

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage) {
    let options: dataPreferences.Options = { name: 'myStore', dataGroupId: 'myId' };
    dataPreferences.removePreferencesFromCacheSync(this.context, options);
  }
}

Options10+

Preferences实例配置选项。

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

名称 类型 必填 说明
name string Preferences实例的名称。
dataGroupId string|null|undefined 应用组ID,需要向应用市场获取。
为可选参数。指定在此dataGroupId对应的沙箱路径下创建Preferences实例。当此参数不填时,默认在本应用沙箱目录下创建Preferences实例。
模型约束: 此属性仅在Stage模型下可用。

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>、Uint8Array类型。
callback AsyncCallback<ValueType> 回调函数。当获取成功时,err为undefined,data为键对应的值;否则err为错误对象。

示例:

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

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

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>、Uint8Array类型。

返回值:

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

示例:

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

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

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>、Uint8Array类型。

返回值:

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

示例:

let value: dataPreferences.ValueType = preferences.getSync('startup', 'default');

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

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

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

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

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

let value = preferences.getAllSync();
let allKeys = getObjKeys(value);
console.info('getAll keys = ' + allKeys);
console.info("getAll object = " + JSON.stringify(value));

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>、Uint8Array类型。
callback AsyncCallback<void> 回调函数。当数据写入成功,err为undefined;否则为错误对象。

示例:

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

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'.");
})

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>、Uint8Array类型。

返回值:

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

示例:

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

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

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>、Uint8Array类型。

示例:

preferences.putSync('startup', 'auto');

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';

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

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';

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

hasSync10+

hasSync(key: string): boolean

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

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

参数:

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

返回值:

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

示例:

let isExist: boolean = preferences.hasSync('startup');
if (isExist) {
  console.info("The key 'startup' is contained.");
} else {
  console.info("The key 'startup' dose not contain.");
}

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';

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'.");
})

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';

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

deleteSync10+

deleteSync(key: string): void

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

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

参数:

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

示例:

preferences.deleteSync('startup');

flush

flush(callback: AsyncCallback<void>): void

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

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

参数:

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

示例:

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

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

flush

flush(): Promise<void>

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

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

返回值:

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

示例:

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

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

clear

clear(callback: AsyncCallback<void>): void

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

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

参数:

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

示例:

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

preferences.clear((err: BusinessError) =>{
  if (err) {
    console.error("Failed to clear. code =" + err.code + ", message =" + err.message);
    return;
  }
  console.info("Succeeded in clearing.");
})

clear

clear(): Promise<void>

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

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

返回值:

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

示例:

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

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

clearSync10+

clearSync(): void

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

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

示例:

preferences.clearSync();

on('change')

on(type: 'change', callback: Callback<string>): void

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

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

参数:

参数名 类型 必填 说明
type string 事件类型,固定值'change',表示数据变更。
callback Callback<string> 回调函数。

示例:

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: Callback<string>): void

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

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

参数:

参数名 类型 必填 说明
type string 事件类型,固定值'multiProcessChange',表示多进程间的数据变更。
callback Callback<string> 回调函数。

错误码:

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

错误码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?: Callback<string>): void

取消订阅数据变更。

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

参数:

参数名 类型 必填 说明
type string 事件类型,固定值'change',表示数据变更。
callback Callback<string> 需要取消的回调函数,不填写则全部取消。

示例:

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?: Callback<string>): void

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

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

参数:

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

示例:

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> 表示值类型为字符串类型的数组。
Uint8Array11+ 表示值类型为8位无符号整型的数组。