openharmony 鸿蒙 js-apis-settings

2025-06-12 浏览 (1)

@ohos.settings (Data Item Settings)

The settings module provides APIs for setting data items.

NOTE

  • The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.

  • If no value is obtained for the accessed data item, it indicates that the current system app does not add the value of the data item to the database.

Modules to Import

import settings from '@ohos.settings';

domainName

Provides the domain name.

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
DEVICE_SHARED11+stringYesYesShared device domain.
USER_PROPERTY11+stringYesYesUser property domain.

date

Provides data items for setting the time and date formats. (Not supported yet.)

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
DATE_FORMATstringYesYesDate format.
The value can be mm/dd/yyyy, dd/mm/yyyy, or yyyy/mm/dd, where mm indicates the month, dd indicates the day, and yyyy indicates the year.
TIME_FORMATstringYesYesTime format. The options are as follows:
- 12: 12-hour format.
- 24: 24-hour format.
AUTO_GAIN_TIMEstringYesYesWhether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).
The value true means that the date, time, and time zone are automatically obtained from NITZ;
false means the opposite.
AUTO_GAIN_TIME_ZONEstringYesYesWhether the time zone is automatically obtained from NITZ.
The value true means that the time zone is automatically obtained from NITZ;
false means the opposite.

display

Provides data items for setting the display effects. (Not supported yet.)

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
FONT_SCALEstringYesYesScale factor of the font. The value is a floating point number. (In the current version, only fixed values can be queried.)
SCREEN_BRIGHTNESS_STATUSstringYesYesScreen brightness, with the value ranging from 0 to 255.
AUTO_SCREEN_BRIGHTNESSstringYesYesWhether automatic screen brightness adjustment is enabled.
- AUTO_SCREEN_BRIGHTNESS_MODE: Automatic screen brightness adjustment is enabled.
- MANUAL_SCREEN_BRIGHTNESS_MODE: Automatic screen brightness adjustment is disabled.
AUTO_SCREEN_BRIGHTNESS_MODEnumberYesYesValue of AUTO_SCREEN_BRIGHTNESS when automatic screen brightness adjustment is enabled.
MANUAL_SCREEN_BRIGHTNESS_MODEnumberYesYesValue of AUTO_SCREEN_BRIGHTNESS when automatic screen brightness adjustment is disabled.
SCREEN_OFF_TIMEOUTstringYesYesWaiting time for the device to enter the sleep state when not in use (unit: ms).
DEFAULT_SCREEN_ROTATIONstringYesYesThis attribute is invalid when screen auto-rotation is enabled; otherwise, the following options are available:
- 0: The screen rotates by 0 degrees.
- 1: The screen rotates by 90 degrees.
- 2: The screen rotates by 180 degrees.
- 3: The screen rotates by 270 degrees.
ANIMATOR_DURATION_SCALEstringYesYesScale factor for the animation duration, which affects the start delay and duration of all such animations.
If the value is 0, the animation ends immediately. The default value is 1.
TRANSITION_ANIMATION_SCALEstringYesYesScale factor for transition animations.
The value 0 indicates that the transition animations are disabled.
WINDOW_ANIMATION_SCALEstringYesYesScale factor for normal window animations.
The value 0 indicates that window animations are disabled.
DISPLAY_INVERSION_STATUSstringYesYesWhether display color inversion is enabled.
- 1: Display color inversion is enabled.
- 0: Display color inversion is disabled.

general

Provides data items for setting the general information about the device. (Not supported yet.)

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
SETUP_WIZARD_FINISHEDstringYesYesWhether the startup wizard is running.
- If the value is 0, the startup wizard is not running.
- If the value is not 0, the startup wizard is running.
END_BUTTON_ACTIONstringYesYesAction after the call end button is pressed if the user is not in a call.
- 0: Nothing happens.
- 1: The home screen is displayed.
- 2: The device enters sleep mode and the screen is locked.
- 3: The home screen is displayed. If the focus is already on the home screen, the device will enter sleep mode.
ACCELEROMETER_ROTATION_STATUSstringYesYesWhether the accelerometer is used to change screen orientation, that is, whether to enable auto-rotation.
- 1: The accelerometer is used.
- 0: The accelerometer is not used.
DEVICE_PROVISION_STATUSstringYesYesWhether the device is preconfigured.
On a multi-user device with a single system user, the screen may be locked when the value is true. In addition, other features cannot be started on the system user unless they are marked to display on the lock screen.
HDC_STATUSstringYesYesWhether the hard disk controller (HDC) on the USB device is enabled.
- true: HDC is enabled.
- false: HDC is disabled.
BOOT_COUNTINGstringYesYesNumber of boot operations after the device is powered on.
CONTACT_METADATA_SYNC_STATUSstringYesYesWhether contacts metadata synchronization is enabled.
- true: Contacts metadata synchronization is enabled.
- false: Contacts metadata synchronization is disabled.
DEVICE_NAMEstringYesYesDevice name.
USB_STORAGE_STATUSstringYesYesWhether USB mass storage is enabled.
- true: USB mass storage is enabled.
- false: USB mass storage is disabled.
DEBUGGER_WAITINGstringYesYesWhether the device waits for the debugger when starting an application to debug.
- 1: The device waits for the debugger.
- 0: The device does not wait for the debugger. In this case, the application runs normally.
DEBUG_APP_PACKAGEstringYesYesBundle name of the application to be debugged.
ACCESSIBILITY_STATUSstringYesYesWhether accessibility is enabled.
- 1: Accessibility is enabled.
- 0: Accessibility is disabled.
ACTIVATED_ACCESSIBILITY_SERVICESstringYesYesList of activated accessibility features.
GEOLOCATION_ORIGINS_ALLOWEDstringYesYesDefault geographic location that can be used by the browser. Multiple geographic locations are separated by spaces.
SKIP_USE_HINTSstringYesYesWhether the application should attempt to skip all introductory hints at the first startup. This feature is intended for temporary or experienced users.
- 1: The application attempts to skip all introductory hints at the first startup.
- 0: The application does not skip all introductory hints at the first startup.
TOUCH_EXPLORATION_STATUSstringYesYesWhether touch exploration is enabled.
- 1: Touch exploration is enabled.
- 0: Touch exploration is disabled.

input

Provides data items for setting input methods. (Not supported yet.)

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
DEFAULT_INPUT_METHODstringYesYesDefault input method and its ID.
ACTIVATED_INPUT_METHOD_SUB_MODEstringYesYesType and ID of the default input method keyboard.
ACTIVATED_INPUT_METHODSstringYesYesList of activated input methods.
The list is a string that contains the IDs and keyboard types of activated input methods.
The IDs are separated by colons (:), and keyboard types are separated by semicolons (;).
An example format is ima0:keyboardType0;keyboardType1;ima1:ima2:keyboardTypes0, where ima indicates the ID of an input method, and keyboardType indicates the keyboard type.
SELECTOR_VISIBILITY_FOR_INPUT_METHODstringYesYesWhether the input method selector is visible.
- 1: The input method selector is visible.
- 0: The input method selector is invisible.
AUTO_CAPS_TEXT_INPUTstringYesYesWhether automatic capitalization is enabled for the text editor.
- 0: Automatic capitalization is disabled.
- 1: Automatic capitalization is enabled.
AUTO_PUNCTUATE_TEXT_INPUTstringYesYesWhether automatic punctuation is enabled for the text editor. Automatic punctuation enables the text editor to convert two spaces into a period (.) and a space.
- 0: Automatic punctuation is disabled.
- 1: Automatic punctuation is enabled.
AUTO_REPLACE_TEXT_INPUTstringYesYesWhether autocorrect is enabled for the text editor. Autocorrect enables the text editor to correct typos.
- 0: Autocorrect is disabled.
- 1: Autocorrect is enabled
SHOW_PASSWORD_TEXT_INPUTstringYesYesWhether password presentation is enabled in the text editor. Password presentation enables the text editor to show password characters when the user types them.
- 0: Password presentation is disabled.
- 1: Password presentation is enabled.

network

Provides data items for setting network information. (Not supported yet.)

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
DATA_ROAMING_STATUSstringYesYesWhether data roaming is enabled.
true: Data roaming is enabled.
false: Data roaming is disabled.
HTTP_PROXY_CFGstringYesYesHost name and port number of the global HTTP proxy. The host name and port number are separated by a colon (:).
NETWORK_PREFERENCE_USAGEstringYesYesUser preferences for the network to use.

phone

Provides data items for setting the modes of answering incoming and outgoing calls. (Not supported yet.)

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
RTT_CALLING_STATUSstringYesYesWhether the real-time text (RTT) feature is enabled. If this feature is enabled, incoming and outgoing calls are answered as RTT calls when supported by the device and carrier.
1: RTT is enabled.
0: RTT is disabled.

sound

Provides data items for setting the sound effects. (Not supported yet.)

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
VIBRATE_WHILE_RINGINGstringYesYesWhether the device vibrates when it is ringing for an incoming call. This attribute is applicable to the phone and settings applications
and affects only the scenario where the device rings for an incoming call. It does not affect any other application or scenario.
DEFAULT_ALARM_ALERTstringYesYesStorage area of the system default alarms and alerts.
DTMF_TONE_TYPE_WHILE_DIALINGstringYesYesType of the dual tone multi-frequency (DTMF) tone played while dialing.
0: normal short tone.
1: long tone.
DTMF_TONE_WHILE_DIALINGstringYesYesWhether the DTMF tone is played when dialing.
1: DTMF tone is played when dialing.
0: DTMF tone is not played when dialing.
AFFECTED_MODE_RINGER_STREAMSstringYesYesEffect on audio streams determined by changes in the ringing mode and Do Not Disturb (DND) mode. If you want a specific audio stream to be affected by changes of the ringing mode and DDN mode, set the corresponding bit to 1.
AFFECTED_MUTE_STREAMSstringYesYesAudio streams affected by the mute mode. If you want a specific audio stream to remain muted in mute mode, set the corresponding bit to 1.
DEFAULT_NOTIFICATION_SOUNDstringYesYesStorage area of the system default notification tone.
DEFAULT_RINGTONEstringYesYesStorage area of the system default ringtone.
SOUND_EFFECTS_STATUSstringYesYesWhether the sound feature is available.
0: The feature is not available.
1: The feature is available.
VIBRATE_STATUSstringYesYesWhether the device vibrates for an event. This attribute is used inside the system.
1: The device vibrates for an event.
0: The device does not vibrate for an event.
HAPTIC_FEEDBACK_STATUSstringYesYesWhether haptic feedback is enabled.
true: Haptic feedback is enabled.
false: Haptic feedback is disabled.

TTS

Provides data items for setting text-to-speech (TTS) information. (Not supported yet.)

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
DEFAULT_TTS_PITCHstringYesYesDefault pitch of the TTS engine.
100 = 1x. If the value is set to 200, the frequency is twice the normal sound frequency.
DEFAULT_TTS_RATEstringYesYesDefault voice rate of the TTS engine.
100 = 1x.
DEFAULT_TTS_SYNTHstringYesYesDefault TTS engine.
ENABLED_TTS_PLUGINSstringYesYesList of activated plug-in packages used for TTS. Multiple plug-in packages are separated by spaces.

wireless

Provides data items for setting wireless network information. (Not supported yet.)

Attributes

System capability: SystemCapability.Applications.Settings.Core

NameTypeReadableWritableDescription
BLUETOOTH_DISCOVER_ABILITY_STATUSstringYesYesWhether the device can be discovered or connected by other devices through Bluetooth.
0: The device cannot be discovered or connected.
1: The device can be connected but cannot be discovered.
2: The device can be discovered and connected.
BLUETOOTH_DISCOVER_TIMEOUTstringYesYesDuration for discovering a device through Bluetooth, in seconds.
After the duration expires, the device cannot be discovered through Bluetooth.
AIRPLANE_MODE_RADIOSstringYesYesList of radio signals to be disabled when airplane mode is enabled.
Multiple radio signals are separated by commas (,).
The list can include the following: BLUETOOTH_RADIO, CELL_RADIO, NFC_RADIO, and WIFI_RADIO.
BLUETOOTH_RADIOstringYesNoA value of AIRPLANE_MODE_RADIOS to indicate that Bluetooth is disabled in airplane mode.
CELL_RADIOstringYesNoA value of AIRPLANE_MODE_RADIOS to indicate that cellular radio is disabled in airplane mode.
NFC_RADIOstringYesNoA value of AIRPLANE_MODE_RADIOS to indicate that NFC is disabled in airplane mode.
WIFI_RADIOstringYesNoA value of AIRPLANE_MODE_RADIOS to indicate that Wi-Fi is disabled in airplane mode.
BLUETOOTH_STATUSstringYesYesWhether Bluetooth is available.
- true: Bluetooth is available.
- false: Bluetooth is unavailable.
OWNER_LOCKDOWN_WIFI_CFGstringYesYesWhether the Wi-Fi configuration created by the application of the device owner should be locked down.
- true: The Wi-Fi configuration should be locked down.
- false: The Wi-Fi configuration should not be locked down.
WIFI_DHCP_MAX_RETRY_COUNTstringYesYesMaximum number of attempts to obtain an IP address from the DHCP server.
WIFI_TO_MOBILE_DATA_AWAKE_TIMEOUTstringYesYesMaximum duration to hold a wake lock when waiting for the mobile data connection after the Wi-Fi connection is disconnected.
WIFI_STATUSstringYesYesWhether Wi-Fi is available.
- true: Wi-Fi is available.
- false: Wi-Fi is unavailable.
WIFI_WATCHDOG_STATUSstringYesYesWhether Wi-Fi watchdog is available.
- true: Wi-Fi watchdog is available.
- false: Wi-Fi watchdog is unavailable.

settings.setValue10+

setValue(context: Context, name: string, value: string, callback: AsyncCallback<boolean>): void

Sets the value for a data item. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Required permissions: ohos.permission.MANAGE_SETTINGS (available only to system applications)

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
valuestringYesValue of the data item. The value range varies by service.
callbackAsyncCallback<boolean>YesCallback used to return the result. Returns true if the operation is successful; returns false otherwise.

Example

import settings from '@ohos.settings';

// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.)
const context: Context =  getContext(this);
settings.setValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (status) => {
  console.log('Callback return whether value is set.');
});

settings.setValue10+

setValue(context: Context, name: string, value: string): Promise<boolean>

Sets the value for a data item. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Required permissions: ohos.permission.MANAGE_SETTINGS (available only to system applications)

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
valuestringYesValue of the data item. The value range varies by service.

Return value

TypeDescription
Promise<boolean>Promise used to return the result. Returns true if the operation is successful; returns false otherwise.

Example

import settings from '@ohos.settings';

// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.)
const context: Context =  getContext(this);
settings.setValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100').then((status) => {
  console.log('Callback return whether value is set.');
});

settings.setValue11+

setValue(context: Context, name: string, value: string, domainName: string): Promise<boolean>

Sets the value for a data item. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Required permissions:

  • ohos.permission.MANAGE_SETTINGS for writing the DEVICE_SHARED and USER_PROPERTY fields (available only to system applications);
  • ohos.permission.MANAGE_SECURE_SETTINGS for writing the USER_SECURITY field (available only to system applications)

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
valuestringYesValue of the data item. The value range varies by service.
domainNamestringYesDomain name to set.
- domainName.DEVICE_SHARED:
   shared device domain
- domainName.USER_PROPERTY:
   user property domain
- domainName.USER_SECURITY:
   user security domain (for system applications only)

Return value

TypeDescription
Promise<string>Promise used to return the result. Returns true if the operation is successful; returns false otherwise.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
201Permission denied.

Example

import settings from '@ohos.settings';

// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.)
const context: Context =  getContext(this);
settings.setValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', settings.domainName.DEVICE_SHARED).then((status) => {
  console.log(`callback:return whether value is set.`)
});

settings.getValue10+

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

Obtains the value of a data item in the database. This API uses an asynchronous callback to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
callbackAsyncCallback<string>YesCallback used to return the value of the data item.

Example

import settings from '@ohos.settings';
const context: Context =  getContext(this);
settings.getValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, (err, value) => {
  if (err) {
    console.error(`Failed to get the setting. ${err.message} `);
    return;
  }
  console.log(`callback:value -> ${value}`)
});

settings.getValue10+

getValue(context: Context, name: string): Promise<string>

Obtains the value of a data item in the database. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items

Return value

TypeDescription
Promise<string>Promise used to return the result. return the value of the data item.

Example

import settings from '@ohos.settings';
const context: Context =  getContext(this);
settings.getValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS).then((value) => {
  console.log(`promise:value -> ${value}`)
});

settings.getValue11+

getValue(context: Context, name: string, domainName: string): Promise<string>;

Obtains the value of a data item in the database. This API uses a promise to return the result.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Required permissions:

  • ohos.permission.MANAGE_SECURE_SETTINGS for reading the USER_SECURITY field (available only to system applications)

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
domainNamestringYesDomain name to set.
- domainName.DEVICE_SHARED:
   shared device domain
- domainName.USER_PROPERTY:
   user property domain
- domainName.USER_SECURITY:
   user security domain (for system applications only)

Return value

TypeDescription
Promise<string>Promise used to return the result. return the value of the data item.

Example

import settings from '@ohos.settings';

// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the getValue API will update its value.)
const context: Context =  getContext(this);
settings.getValue(context, settings.display.SCREEN_BRIGHTNESS_STATUS, settings.domainName.DEVICE_SHARED).then((value) => {
  console.log(`Promise:value -> ${value}`);
});

settings.getValueSync10+

getValueSync(context: Context, name: string, defValue: string): string;

Obtains the value of a data item. Unlike getValue, this API returns the result synchronously.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
defValuestringYesDefault value, which is returned when the value of a data item is not found in the database. Set this parameter as needed.

Return value

TypeDescription
stringValue of the data item.

Example

import settings from '@ohos.settings';

// Obtain the value of SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database).
const context: Context =  getContext(this);
let value = settings.getValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '10');

settings.getValueSync11+

getValueSync(context: Context, name: string, defValue: string, domainName: string): string;

Obtains the value of a data item. Unlike getValue, this API returns the result synchronously.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Required permissions:

  • ohos.permission.MANAGE_SECURE_SETTINGS for reading the USER_SECURITY field (available only to system applications)

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
defValuestringYesValue of the data item. The value range varies by service.
domainNamestringYesDomain name to set.
- domainName.DEVICE_SHARED:
   shared device domain
- domainName.USER_PROPERTY:
   user property domain
- domainName.USER_SECURITY:
   user security domain (for system applications only)

Return value

TypeDescription
stringValue of the data item.

Example

import settings from '@ohos.settings';

// Update the value of .SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database).
const context: Context =  getContext(this);
let value = settings.getValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100',  settings.domainName.DEVICE_SHARED);

settings.setValueSync10+

setValueSync(context: Context, name: string, value: string): boolean

Sets the value for a data item. Unlike setValue, this API returns the result synchronously.

  • If the specified data item exists in the database, the setValueSync method updates the value of the data item.
  • If the data item does not exist in the database, the setValueSync method inserts the data item into the database.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Required permissions: ohos.permission.MANAGE_SETTINGS (available only to system applications)

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
valuestringYesValue of the data item. The value range varies by service.

Return value

TypeDescription
booleanResult indicating whether the value is set successfully. Returns true if the value is set successfully; returns false otherwise.

Example

import settings from '@ohos.settings';

// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync API will update its value.)
const context: Context =  getContext(this);
let ret = settings.setValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100');

settings.setValueSync11+

setValueSync(context: Context, name: string, value: string, domainName: string): boolean

Sets the value for a data item. Unlike setValue, this API returns the result synchronously.

  • If the specified data item exists in the database, the setValueSync method updates the value of the data item.
  • If the data item does not exist in the database, the setValueSync method inserts the data item into the database.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Required permissions:

  • ohos.permission.MANAGE_SETTINGS for writing the DEVICE_SHARED and USER_PROPERTY fields (available only to system applications);
  • ohos.permission.MANAGE_SECURE_SETTINGS for writing the USER_SECURITY field (available only to system applications)

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
valuestringYesValue of the data item. The value range varies by service.
domainNamestringYesDomain name to set.
- domainName.DEVICE_SHARED:
   shared device domain
- domainName.USER_PROPERTY:
   user property domain
- domainName.USER_SECURITY:
   user security domain (for system applications only)

Return value

TypeDescription
booleanResult indicating whether the value is set successfully. Returns true if the value is set successfully; returns false otherwise.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
201Permission denied.

Example

import settings from '@ohos.settings';

// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync API will update its value.)
const context: Context =  getContext(this);
let ret = settings.setValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', settings.domainName.DEVICE_SHARED);

settings.registerKeyObserver11+

registerKeyObserver(context: Context, name: string, domainName: string, observer:AsyncCallback<void>): boolean

Registers an observer in the specified context so that the specified data item can be observed in the specified domain name. When the data item value changes, the registered callback is called. Returns true if the registration is successful; returns false otherwise.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
domainNamestringYesDomain name to set.
- domainName.DEVICE_SHARED:
   shared device domain
- domainName.USER_PROPERTY:
   user property domain
- domainName.USER_SECURITY:
   user security domain (for system applications only)
observerAsyncCallback<void>YesCallback used to return the value of the data item.

Return value

TypeDescription
booleanResult indicating whether the value is set successfully. Returns true if the value is set successfully; returns false otherwise.

Example

import settings from '@ohos.settings';

const context: Context =  getContext(this);
settings.registerKeyObserver(context, settings.display.SCREEN_BRIGHTNESS_STATUS, settings.domainName.DEVICE_SHARED, (err, val) => {
  if (err) {
    console.error(`Failed to get the setting. ${err.message} `);
    return;
  }
  console.log(`callback:value -> ${JSON.stringify(val)}`)
  let value:string = settings.getValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '10');
  console.log(`Promise:value -> ${value}`);
});

settings.unregisterKeyObserver11+

unregisterKeyObserver(context: Context, name: string, domainName: string): boolean

Unregisters the observer under the specified domain name. This API returns the result synchronously.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.Applications.Settings.Core

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
domainNamestringYesDomain name to set.
- domainName.DEVICE_SHARED:
   shared device domain
- domainName.USER_PROPERTY:
   user property domain
- domainName.USER_SECURITY:
   user security domain (for system applications only)

Return value

TypeDescription
booleanWhether the observer under the specified domain name is successfully unregistered. Returns true if the deregistration is successful; returns false otherwise.

Example

import settings from '@ohos.settings';

const context: Context =  getContext(this);
let ret = settings.unregisterKeyObserver(context, settings.display.SCREEN_BRIGHTNESS_STATUS,  settings.domainName.DEVICE_SHARED);

settings.openNetworkManagerSettings18+

openNetworkManagerSettings(context: Context): Promise<boolean>

Opens the network manager settings page. This API uses a promise to return the result.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
contextContextYesApplication context. Only UIAbilityContext and ExtensionContext are supported.
For details about the application context of the stage model, see Context.

Return value

TypeDescription
Promise<string>Promise used to return the result. Returns true if the operation is successful; returns false otherwise.

Error codes

For details about the error codes, see Settings Error Codes.

IDError Message
14800000Parameter error.
14800010Original service error.

Example

import settings from '@ohos.settings';

// Redirect to the network manager settings page.
const context: Context =  getContext(this);
settings.openNetworkManagerSettings(context).then((status) => {
  console.log(`callback:return whether settings is open.`)
});

settings.enableAirplaneMode

enableAirplaneMode(enable: boolean, callback: AsyncCallback<void>): void

Enables or disables airplane mode. This API uses an asynchronous callback to return the result. (Not supported yet.)

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
enablebooleanYesWhether airplane mode is enabled. true means that airplane mode is enabled, and false means the opposite.
callbackAsyncCallback<void>YesCallback used to return the result.

Example

let isEnabled :boolean = true;
settings.enableAirplaneMode(isEnabled, (err:Error) => {
    if (err) {
        console.log('Failed to enable AirplaneMode.');
        return;
    }
    console.log('Return true if enable.');
})

settings.enableAirplaneMode

enableAirplaneMode(enable: boolean): Promise<void>

Enables or disables airplane mode. This API uses a promise to return the result. (Not supported yet.)

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
enablebooleanYesWhether airplane mode is enabled. true means that airplane mode is enabled, and false means the opposite.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Example

let isEnabled :boolean = true;
settings.enableAirplaneMode(isEnabled).then(() => {
  console.log('Succeeded in enabling AirplaneMode.');
}).catch((err:Error) => {
  console.log(`Failed to enable AirplaneMode. Cause: ${err}`);
})

settings.canShowFloating

canShowFloating(callback: AsyncCallback<boolean>): void

Checks whether the application can be displayed in a floating window. This API uses an asynchronous callback to return the result. (Not supported yet.)

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<boolean>YesCallback used to return the result.
The value true means the application can be displayed in a floating window; false means the opposite.

Example

settings.canShowFloating((err:Error, status: boolean) => {
  if (err) {
    console.error(`Failed to Checks whether a specified application can show as float window ${err.message} `);
    return;
  }
  console.log('Checks whether a specified application can show as float window.');
});

settings.canShowFloating

canShowFloating(): Promise<boolean>

Checks whether the application can be displayed in a floating window. This API uses a promise to return the result. (Not supported yet.)

System capability: SystemCapability.Applications.Settings.Core

Return value

TypeDescription
Promise<boolean>Promise used to return the result.
The value true means the application can be displayed in a floating window; false means the opposite.

Example

settings.canShowFloating().then((status:boolean) => {
    console.log('Checks whether a specified application can show as float window.');
});

settings.getUriSync8+

getUriSync(name: string): string

Obtains the URI of a data item. (Not supported yet.)

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items

Return value

TypeDescription
stringURI of the data item.

Example

// Obtain the URI of a data item.
let uriVar:string = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);

settings.getURI(deprecated)

getURI(name: string, callback: AsyncCallback<object>): void

Obtains the URI of a data item. This API uses an asynchronous callback to return the result. (Not supported yet.)

NOTE

This API is supported since API version 7 and deprecated since API version 9. No substitute API is provided.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
callbackAsyncCallback<object>YesCallback used to return the result. Obtains the URI of a data item.

Example

settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS, (uri:string) => {
    console.log(`callback:uri -> ${JSON.stringify(uri)}`)
})

settings.getURI(deprecated)

getURI(name: string): Promise<object>

Obtains the URI of a data item. This API uses a promise to return the result. (Not supported yet.)

NOTE

This API is supported since API version 7 and deprecated since API version 9. No substitute API is provided.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items

Return value

TypeDescription
Promise<object>Promise used to return the result. return the URI of the data item.

Example

settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS).then((uri:string) => {
    console.log(`promise:uri -> ${JSON.stringify(uri)}`)
})

settings.getValue(deprecated)

getValue(dataAbilityHelper: DataAbilityHelper, name: string, callback: AsyncCallback<object>): void

Obtains the value of a data item in the database. This API uses an asynchronous callback to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getValue() instead.

Model restriction: This API can be used only in the FA model.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
dataAbilityHelperDataAbilityHelperYesDataAbilityHelper class.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
callbackAsyncCallback<object>YesCallback used to return the value of the data item.

Example

import featureAbility from '@ohos.ability.featureAbility';

let uri:string = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, (err:Error, value:string) => {
    if (err) {
        console.error(`Failed to get the setting. ${err.message} `);
        return;
    }
    console.log(`callback:value -> ${JSON.stringify(value)}`)
});

settings.getValue(deprecated)

getValue(dataAbilityHelper: DataAbilityHelper, name: string): Promise<object>

Obtains the value of a data item in the database. This API uses a promise to return the result.

NOTE

This API is supported since API version 7 and deprecated since API version 9. You are advised to use getValue() instead.

Model restriction: This API can be used only in the FA model.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
dataAbilityHelperDataAbilityHelperYesDataAbilityHelper class.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items

Return value

TypeDescription
Promise<object>Promise used to return the result. return the value of the data item.

Example

import featureAbility from '@ohos.ability.featureAbility';

let uri:string = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS).then((value:string) => {
    console.log(`promise:value -> ${JSON.stringify(value)}`)
});

settings.getValueSync(deprecated)

getValueSync(dataAbilityHelper: DataAbilityHelper, name: string, defValue: string): string

Obtains the value of a data item. Unlike getValue, this API returns the result synchronously.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use getValueSync() instead.

Model restriction: This API can be used only in the FA model.

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
dataAbilityHelperDataAbilityHelperYesDataAbilityHelper class.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
defValuestringYesDefault value, which is returned when the value of a data item is not found in the database. Set this parameter as needed.

Return value

TypeDescription
stringValue of the data item.

Example

import featureAbility from '@ohos.ability.featureAbility';

// Obtain the value of SCREEN_BRIGHTNESS_STATUS (this data item already exists in the database).
let uri:string = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
let value:string = settings.getValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '10');

settings.setValueSync(deprecated)

setValueSync(dataAbilityHelper: DataAbilityHelper, name: string, value: string): boolean

Sets the value for a data item. Unlike setValue, this API returns the result synchronously.

  • If the specified data item exists in the database, the setValueSync method updates the value of the data item.
  • If the data item does not exist in the database, the setValueSync method inserts the data item into the database.

NOTE

This API is supported since API version 8 and deprecated since API version 9. You are advised to use setValueSync() instead.

Model restriction: This API can be used only in the FA model.

Required permissions: ohos.permission.MANAGE_SETTINGS (available only to system applications)

System capability: SystemCapability.Applications.Settings.Core

Parameters

NameTypeMandatoryDescription
dataAbilityHelperDataAbilityHelperYesDataAbilityHelper class.
namestringYesName of the target data item. Data items can be classified as follows:
- Existing data items in the database
- Custom data items
valuestringYesValue of the data item. The value range varies by service.

Return value

TypeDescription
booleanResult indicating whether the value is set successfully. Returns true if the value is set successfully; returns false otherwise.

Example

import featureAbility from '@ohos.ability.featureAbility';

// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValueSync API will update its value.)
let uri:string = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
let ret:string = settings.setValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100');

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Basic Services Kit

harmony 鸿蒙DeviceInfo

harmony 鸿蒙InitSync

harmony 鸿蒙OH_Print

harmony 鸿蒙OsAccount

harmony 鸿蒙Pasteboard

harmony 鸿蒙Print_Margin

harmony 鸿蒙Print_PageSize

harmony 鸿蒙Print_PrintAttributes

harmony 鸿蒙Print_PrintDocCallback

  • 所属分类: 后端技术
  • 本文标签: 鸿蒙 软件
  • 版权声明: 本文链接 https://seaxiang.com/blog/LZitvY