harmony-utils

harmony-utils(API12+)

🏆Introduction and Description

harmony-utils A HarmonyOS tool library with rich features and extremely easy to use, with the help of many practical tools, is committed to helping developers quickly build Hongmeng applications. Its encapsulated tools cover APP, device, screen, authorization, notification, inter-thread communication, pop-up frames, toast, biometric authentication, user preferences, taking photos, albums, scanning codes, files, logs, exception capture, characters, strings, numbers, collections, dates, random, base64, encryption, decryption, JSON and other functions, which can meet various development needs.
picker_utils It is a sub-store split by harmony-utils, including PickerUtil, PhotoHelper, and ScanUtil.

📚 Warm reminder: 📕 Harmony-utils is a lightweight framework that integrates more than 50 tool classes, but it is only 130KB in size. Achieve the ultimate balance between tool count and lightweight performance. 📙 Starting from version 1.3.2, the methods in the harmony-utils tool library will no longer be directly discarded. Please feel free to use it in third-party libraries and projects. 📒 In the update record, each version number has the corresponding minimum development tool version, such as: "DevEco Studio 5.1.0 Release". 📗 Please read the documentation carefully and view the use case before using the framework. 🙏 📘 See, please! Follow the official account of "Elder Tong" quickly, and you are waiting for you to unlock it. 📔 Creation is not easy, please give Elder Tong a thumbs up 👍github❤️ gitee❤️ 三方库❤️

🌞Download, installation and use instructions 🙏

ohpm i @pura/harmony-utils
OpenHarmony ohpm environment configuration and more, please refer to如何安装 OpenHarmony ohpm 包

全局初始化方法,从1.2.0版本开始,在UIAbility的onCreate方法中初始化 AppUtil.init()

  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    AppUtil.init(this.context);
  }

📂Module Introduction

ModuleIntroduction
AppUtilAPP-related tool categories
DeviceUtilDevice-related tools
WindowUtilWindow related tool classes
DisplayUtilScreen related tools
PermissionUtilApplication Authorization Tools
AuthUtilMobile phone biometric authentication (fingerprint, face, password) tools
NetworkUtilNetwork related tools
FileUtilFile operation related tool categories
ImageUtilPicture-related tools
PreviewUtilFile Preview Tools
LocationUtilPositioning Tool Class (WGS-84 Coordinate System)
LogUtilLog Tools
CrashUtilGlobal exception capture, crash log collection
EmitterUtilEmitter tool class (for inter-thread communication)
WantUtilWant Tools
KvUtilKey-value database tool class
PreferencesUtilPreferences (User Preferences) Tool Class
CacheUtilCache Tools
LRUCacheUtilLRUCache Cache Tool Class
NotificationUtilNotification Tools
SnapshotUtilComponent screenshot and window screenshot tool class.
KeyboardUtilKeyboard Tools
PasteboardUtilClipboard Tools
AssetUtilKey Asset Storage Service Tools
ResUtilResource Tools
ObjectUtilObject Tool Class
JSONUtilJSON Tool Class
DateUtilDate Tools
Base64UtilBase64 Tools
StrUtilString Tool Class
CharUtilCharacter Tools
NumberUtilnumber tool class
ArrayUtilCollection Tools
RandomUtilRandom Tools
RegexUtilRegular Tools
TypeUtilType Checking Tool Class
FormatUtilFormat Tools
ClickUtilThrottle, anti-shake tool class (used to click events to prevent buttons from being clicked repeatedly)
TempUtilTemperature conversion tool category
DialogUtilPop-up tool class (AlertDialog)
ToastUtilToast Tools (promptAction)
SM2, SM3, SM4,
AES, DES, RSA,
MD5, SHA, ECDSA,
CryptoUtil,
CryptoHelper
Encryption and decryption algorithm tool class
CryptoUtil: Encryption and decryption utility class, used with each encryption module.
CryptoHelper: Encrypt and decrypt data type conversion.
PickerUtilSelection and saving of photos, files (files, pictures, videos, audio), tools.拆分至 picker_utils
PhotoHelperPhoto Album related tool category.拆分至 picker_utils
ScanUtilCode tool category (scan code, code image generation, picture identification).拆分至 picker_utils


MethodsIntroduction
initInitialization method, cache global variables, and initialize the method in UIAbility's onCreate method
isApiSupportedCheck whether the API version is safe
getApplicationContextAbility to get application-level context, ApplicationContext
getContextGet context, common.UIAbilityContext
getUIContextGet UIContext
getWindowStageGet WindowStage
getMainWindowGet the main window
getConfigurationGet the application's Configuration
setGrayScaleSet grayscale, APP has one-click graying
setColorModeSet the applied color mode. Only main thread calls are supported. Set color mode, including: dark mode, light mode, no setting (follow system)
getColorModeGet the color mode of the application
setFontSet the font type of the application. Only main thread calls are supported
setFontSizeScaleSet the applied font size scaling ratio. Only main thread calls are supported.
getFontSizeScaleGet the app font size scaling
setLanguageSet the language of the application
getLanguageGet the language of the application
setSupportedProcessCacheSet whether the application itself supports cache and starts quickly
clearUpApplicationDataClean up the application's own data and revoke the application's permissions to the user.
killAllProcessesTerminate all processes of the application, and the application life cycle will not be completed normally when the process exits.
restartAppRestart the app and pull up the specified UIAbility of itself. The onDestroy callback will not be received during restart.
exitActively exit the entire application; after calling this method, the tasks in the task center will not be cleaned by default. If you need to clean it, you need to configure removeMissionAfterTerminate to true.
getRunningProcessInformationGet information about running the process
onApplicationStateChangeRegister listening to changes before and after the current application
offApplicationStateChangeCancel listening to the application's front and backend switching events
onEnvironmentRegister monitoring of system environment changes
offEnvironmentCancel monitoring of system environment changes
onAbilityLifecycleRegister to listen for in-app lifecycle
offAbilityLifecycleCancel listen for in-app lifecycle
getKeyboardAvoidModeGet page avoidance mode when virtual keyboard is lifted (OFFSET-up mode, RESIZE-compression mode)
setKeyboardAvoidModeSet the page avoidance mode when the virtual keyboard pops up
isPortraitIs the current device displayed in a vertical screen
isLandscapeIs the current device displayed in landscape mode
getStatusBarHeightGet the height of the status bar in px
getNavigationIndicatorHeightGet the height of the bottom navigation bar in px.
setStatusBarSet the immersive status bar (need to be used with getStatusBarHeight and getNavigationIndicatorHeight)
getBundleInfo
getBundleInfoSync
Get the BundleInfo for the current application
getAppInfo
getAppInfoSync
Get application configuration information
getSignatureInfo
getSignatureInfoSync
Get the signature information of the application package
getBundleNameGet the name of the application package
getVersionCodeGet application version number
getVersionNameGet application version name
getTargetVersionGet the target version of the application running
getInstallTimeApplication Package Installation Time
getUpdateTimeApplication Package Update Time
getAppProvisionTypeGet the type of application signature certificate file, divided into two types: debug and release.
debugIndicates whether the application is in debug mode. A value of true means the application is in debug mode. A value of false means the application is in non-debug mode.
MethodsIntroduction
getDeviceIdGet the device ID (it remains unchanged after uninstalling the APP, and permissions are required: ohos.permission.STORE_PERSISTENT_DATA)
deleteDeviceIdRemove Device ID
getODIDGet the developer's anonymous device identifier, ODID.
getOAIDGet the open anonymous device identifier, OAID.
getAAIDGet AAID.
deleteAAIDDeleteAAID.
getSerialGet the device serial number. Description: Can be used as a unique identification code for the device. Example: The serial number varies with the device.
getUdidGet the device Udid.
getBrandGet the device brand name. Example: HUAWEI.
getProductModelGet certified model. Example: ALN-AL00.
getBrandModelGet the device brand name Certified model. Example: HUAWEI ALN-AL00.
getMarketNameGet the external product series name. Example: HUAWEI Mate 60 Pro.
getHardwareModelGet the hardware version number. Example: HL1CMSM.
getManufactureGet the device manufacturer name. Example: HUAWEI.
getOsFullNameGet system version
getDisplayVersionGet the product version. Example: ALN-AL00 5.0.0.1(XXX)
getBuildVersionGet the Build version number, identifying the version number of the compiled and built
getSdkApiVersionGet the system software API version. Example: 12
getOsVersionGet the OS version number (Major version number, example: 5; Senior version number, example: 0; Feature version number, example: 0).
getAbiListApplication binary interface (Abi). Example: arm64-v8a
getOsReleaseTypeGet the system's publishing type, the values ​​are: Canary, Beta, Release
getDeviceTypeGet the current device type
getDeviceTypeStrGet the current device type and return the string.
getConfiguration
getConfigurationSync
Get the device's Configuration
getDirectionGet the current device screen direction
getDeviceCapability
getDeviceCapabilitySync
Get DeviceCapability for DeviceCapability
getScreenDensityGet the current device screen density
getBatterySOCGet the percentage of battery remaining in the current device.
getBatteryCapacityLevelGet the current device battery level.
getHealthStatusGet the current health status of the device battery.
getBatteryTemperatureGet the current device battery temperature, unit 0.1 degrees Celsius.
getVoltageGet the voltage of the current device battery, unit to microvolts.
getNowCurrentGet the current of the current device battery in milliamperes.
isActiveDetect whether the current device is active. Devices with screens are in a light screen state, while devices without screens are in a non-sleep state.
isStandbyDetect whether the current device enters standby low-power battery life mode.
getPowerModeGet the power mode of the current device.
startVibrationTurn on device vibration
stopVibrationStop the device vibration (according to VIBRATOR_STOP_MODE_TIME mode)
MethodsIntroduction
setPreferredOrientationSet the display direction properties of the window
getPreferredOrientationGet the display direction property of the window, and the main window is called.
setWindowPrivacyModeSet whether the window is in Privacy Mode. For a window set to privacy mode, the content of the window will not be screenshot or recorded
isPrivacyModeWhether the window is privacy mode, the default main window.
setWindowLayoutFullScreenSet whether the layout of the window is an immersive layout (the status bar and navigation bar of the immersive layout are still displayed)
isLayoutFullScreenDetermine whether the window is immersive, the default main window.
setWindowSystemBarPropertiesSet the properties of the three-key navigation bar and status bar in the main window.
getWindowSystemBarPropertiesGet the properties of the three-key navigation bar and status bar in the main window.
setImmersiveModeEnabledStateSet whether the current window is turned on to immersive layout. This call will not change the window mode and window size.
getImmersiveModeEnabledStateCheck whether the current window has enabled immersive layout.
setWindowGrayScaleSet window grayscale. This interface needs to be called after calling loadContent() or setUIContent() to make the window load the page content.
setWindowBackgroundColorSet the background color of the window. Under the Stage model, this interface needs to be used after the loadContent() or setUIContent() call takes effect
setWindowSystemBarEnableSet the visible mode of the three-key navigation bar, status bar, and bottom navigation bar in the main window. The status bar and bottom navigation bar are controlled through status and the three-key navigation bar are controlled through navigation.
setSpecificSystemBarEnabledSet the display and hide of the three-key navigation bar, status bar, and bottom navigation bar in the main window.
setWindowKeepScreenOnSet whether the screen is always on
isKeepScreenOnIs the screen always lit
setWindowBrightnessSet screen brightness value
getBrightnessGet screen brightness. This parameter is a floating point number, and the brightness range that can be set is [0.0, 1.0], which indicates the maximum brightness value when taken 1.0. If the window does not set the brightness value, it means that the brightness follows the system, and the brightness value obtained at this time is -1.
setWindowFocusableSets the scene where the window is focused by clicking or other means, whether the window supports switching the window focus from the focus window before clicking to the window
isFocusableWhether the window is focused, the default main window.
setWindowTouchableSet whether the window is touchable
isTouchableWhether the window is touchable, the default main window.
getWindowPropertiesGet the properties of the current window, the default main window.
getWindowAvoidAreaGet the area to which the current application window content is evaded. For example, when the system bar area, notch screen area, gesture area, soft keyboard area, etc. overlap with the window content, the window content needs to be avoided.
getWindowTypeGets the window type, default main window.
getWindowStatusGet the current application window mode
isFullScreenDetermine whether the window is full screen, the default main window.
isFocusedDetermine whether the current window has been focused
isTransparentWhether the window is transparent, the default main window.
isWindowShowingDetermine whether the current window has been displayed, the default main window.
isWindowSupportWideGamutDetermine whether the current window supports wide color gamut mode, the default main window.
setDialogBackGestureEnabledSet whether the modal window responds to gestures and returns an event, and calls to non-modal windows return an error code
setGestureBackEnabledSet whether the return gesture function is disabled in the current window. It only takes effect in full screen mode of the main window, and does not take effect in 2in1 device.
isGestureBackEnabledGet whether the return gesture function is disabled in the current window. It only takes effect in full screen mode of the main window, and the 2in1 device does not take effect.
createWindowCreate a child window or system window and use Promise asynchronous callback.
findWindowFind the window corresponding to name.
getLastWindowGet the topmost subwindow in the current application. If there is no application subwindow, it returns to the application main window.
shiftAppWindowFocusTransfer window focus from the source window to the target window in the same application, only the focus transfer of the main window and child window of the application is supported.
MethodsIntroduction
getDefaultDisplaySyncGet the current default display object
getPrimaryDisplaySyncGet home screen information. Devices other than 2in1 obtain the Display object with the device's own screen; when the 2in1 device connects to the external screen, it obtains the Display object with the current home screen; when the 2in1 device does not have an external screen, it obtains the Display object with the screen.
getAllDisplaysGet all current display objects, use Promise asynchronous callback
getWidthGet the screen width of the device in px
getHeightGet the screen height of the device in px
getOrientationGet the current direction of the device
getDisplayStateGet the device's status
getCutoutRectGet information on unavailable screen areas such as hole-punch screen, notch screen, waterfall screen, etc. It is recommended to apply layout to avoid this area
getCutoutHeightGet the height of unavailable screen areas such as hole-punch screen, notch screen, unit is px
isFoldableCheck if the device is foldable
getFoldStatusGet the current folding status of the foldable device
getFoldDisplayModeGet the display mode of the foldable device
onFoldStatusChangeTurn on monitoring of folding state changes in folding device
offFoldStatusChangeTurn off monitoring of folding state changes in folding device
onFoldAngleChangeTurn on monitoring of folding angle changes in folding device. If it is a bifold shaft device, there are two angle values; when the charging port is facing downward, the folding shaft one and folding shaft two are respectively from right to left.
offFoldAngleChangeClose the monitoring of folding angle changes in folding equipment
isCapturedCheck whether the device is taking screenshots, projecting, or recording screens.
onCaptureStatusChangeTurn on monitoring of screen capture, projection, and recording status changes.
offCaptureStatusChangeClose monitoring of changes in screen capture, projection, and recording status.

PermissionUtil (apply for authorization tool category)使用案例

MethodsIntroduction
requestPermissionsEasyApply for authorization, and apply for authorization to the user again after refusing (apply for permission, it is recommended to use this method).
checkPermissionsVerify that it is currently authorized
checkRequestPermissionsAfter verifying whether to authorize and apply for authorization
requestPermissionsApply for authorization
requestPermissionOnSettingSecondary application for authorization to the user (single permissions or read and write permission groups, this method is recommended).
requestPermissionOnSettingEasySecondary application for authorization to the user (this method is recommended for multiple permissions).
requestGlobalSwitchUsed to UIAbility/UIExtensionAbility to pull up the global switch to set the pop-up box. In some cases, recording, taking photos and other functions are disabled. The application can pull up this box and ask the user to agree to enable the corresponding functions. If the current global switch status is on, the pop-up box will not be pulled up.

AuthUtil (biological authentication (fingerprint, face, password) tool category for mobile phones)使用案例

MethodsIntroduction
getAvailableStatusQuery whether the authentication capability of the specified type and level supports
onStartEasyStart Authentication, Use fingerprint and password authentication
onStartStart authentication, user-specified type authentication
cancelcancel
generateChallengeGenerate Challenge to prevent replay attacks
getErrorMsgGet error msg
MethodsIntroduction
isDefaultNetMetered
isDefaultNetMeteredSync
Check whether the current data traffic usage on the network is metered
hasDefaultNet
hasDefaultNetSync
Check whether the default data network is activated
getDefaultNet
getDefaultNetSync
Get the default activated data network
getAppNet
getAppNetSync
Get App-bound network information
getAllNets
getAllNetsSync
Get a list of all connected networks
isNetworkAvailableDetermine whether the current device network is available
hasNetMobileDetermine whether the current network is a cellular network (mobile network).
hasNetWiFiDetermine whether the current network is a Wi-Fi network.
hasNetEthernetDetermine whether the current network is an Ethernet network.
hasNetVPNDetermine whether the current network is a VPN network.
hasNetBearTypeWhether the specified network exists
getNetBearTypesGet the network type, the array only contains one specific network type.
getNetBearTypeGet network type
getNetCapabilities
getNetCapabilitiesSync
Get the capability information of the network corresponding to netHandle
getConnectionProperties
getConnectionPropertiesSync
Get the connection information of the network corresponding to netHandle
getIpAddressGet the IP address of the current device (after the device is connected to Wi-Fi)
registerSubscribe to notifications of specified network status changes, support multi-event listening callbacks
unregisterUnsubscribe to notifications about default network status changes
isNRSupportedDetermine whether the current device supports NR (New Radio). That is 5G.
isRadioOnDetermine whether Radio is open
getPrimarySlotIdGet the index number of the card slot where the main card is located
getOperatorNameGet operator name
getNetworkStateGet network status
getNetworkSelectionModeGet the current network selection mode
getSignalInformationGet the list of registered network signal strength information corresponding to the specified SIM card slot.
getNetworkTypeGet network type
getNetworkTypeStrGet the network type and return the character type.
getDefaultCellularDataSlotId
getDefaultCellularDataSlotIdSync
SIM card to get default mobile data
getCellularDataFlowTypeGet the up and down state of cellular data services
getCellularDataStateGet the connection status of the packet switching domain (PS domain)
isCellularDataEnabled
isCellularDataEnabledSync
Check whether cellular data service is enabled
isCellularDataRoamingEnabled
isCellularDataRoamingEnabledSync
Check whether cellular data services are enabled
getDefaultCellularDataSimIdGet the SIM card ID of the default mobile data. Bind with SIM card, incrementing from 1.
isSimActive
isSimActiveSync
Get whether the SIM card is activated when the specified card slot is activated
hasSimCard
hasSimCardSync
Get whether the SIM card is inserted into the specified card slot
getMaxSimCountGet the number of card slots
getSimOperatorNumeric
getSimOperatorNumericSync
Get the home PLMN (Public Land Mobile Network) number of the SIM card in the specified card slot.
getSimSpn
getSimSpnSync
Get the service provider name of the SIM card specified in the card slot
getSimState
getSimStateSync
Get the SIM card status of the specified card slot
getCardType
getCardTypeSync
Get the card type of the SIM card in the specified card slot
MethodsIntroduction
getFilesDirPathGet the folder path or file path in the file directory
getCacheDirPathGet the folder path or file path in the cache directory
getTempDirPathGet the folder path or file path in the temporary directory
hasDirPathDetermine whether it is the complete path
getFileUriGet FileUri through URI or path
getFileNameGet file name through URI or path
getFilePathGet file path through URI or path
getParentUriGet the URI of the corresponding file parent directory through URI or path
getParentPathGet the path name of the corresponding file parent directory through a URI or path
getUriFromPathGet file URI in synchronous way
getFileExtentionGet file suffix based on file name
getFileDirSizeGet the size of all files in the specified folder or the specified file size
isFileDetermine whether a file is a normal file
isDirectoryDetermine whether the file is a directory
rename
renameSync
Rename file or folder, use Promise asynchronous callback
mkdir
mkdirSync
Create a directory. When recursion is specified as true, you can create a directory at multiple levels
rmdir
rmdirSync
Delete the entire directory and use Promise asynchronous callback
unlink
unlinkSync
Delete a single file, use Promise asynchronous callback
access
accessSync
Check whether the file exists and use Promise asynchronous callback
open
openSync
Open file, support using URI to open files
read
readSync
Read data from file
readText
readTextSync
Read files based on text (that is, directly read the text content of the files)
write
writeSync
Write data to file
writeEasyWrite data to a file and close the file
close
closeSync
Close File
listFile
listFileSync
List all file names in the folder, supports recursive listing of all file names (including subdirectories), supports file filtering
stat
statSync
Get file detailed attribute information
copyCopy files or directories, support copy progress monitoring
copyFile
copyFileSync
Copy File
moveFile
moveFileSync
Move File
moveDir
moveDirSync
Move the source folder to the destination path
truncate
truncateSync
Truncate File
lstat
lstatSync
Get link file information
fsync
fsyncSync
Synchronize file data
fdatasync
fdatasyncSync
Implement file content data synchronization
createStream
createStreamSync
Open file stream based on file path
fdopenStream
fdopenStreamSync
Open file stream based on file descriptor
mkdtemp
mkdtempSync
Create a temporary directory
dupConvert file descriptors to File
utimesModify file recent access time attributes
getFormatFileSizeFormat file size
persistPermission
persistPermissionEasy
PersistPermissionEasyPersistPermissionEasyPersistPermissionEasyPersistPermissionEasyPersistPermissionEasyPersistPermissionEasyPersistPermissionEasyPersistPermissionEasyPersistPermissionEasyPersistPermissionEasyPersistPermissionEasy (Permission required: ohos.permission.FILE_ACCESS_PERSIST)
revokePermission
revokePermissionEasy
Unpersistence authorization for multiple selected files or directories uri. (Permission required: ohos.permission.FILE_ACCESS_PERSIST)
activatedPermission
activatePermissionEasy
Enable permissions that have been persisted authorized, otherwise the permissions that have been persisted authorized cannot be used. (Permission required: ohos.permission.FILE_ACCESS_PERSIST)
deactivatePermission
deactivatePermissionEasy
Cancel multiple authorized files or directories. (Permission required: ohos.permission.FILE_ACCESS_PERSIST)
checkPersistentPermissionVerify the selected multiple file or directory URI persistence authorization. (Permission required: ohos.permission.FILE_ACCESS_PERSIST)
MethodsIntroduction
base64ToPixelMapPicture base64 string to PixelMap
pixelMapToBase64StrPixelMap to picture base64 string
savePixelMapSave pixelMap to local
saveImageSourceSave ImageSource to local
createImageSourceCreate image source instance
createIncrementalSourceCreate an image source instance in incremental way
packingFromPixelMapPicture compression or repackaging, use Promise to return the result
packingFromImageSourceImage compression or repackaging, use Promise to return the result
packToFileFromPixelMapEncode the PixelMap image source and package it directly into the file
packToFileFromImageSourceEncode the ImageSource image source and package it directly into the file
getPixelMapFromMediaUser gets the picture in media under the resource directory PixelMap
compressedImageImage compression
compressPhotoPicture compression, return to the compressed picture file path

PreviewUtil (file preview tool class)使用案例

MethodsIntroduction
generatePreviewInfoBuild PreviewInfo from file uri
openPreviewOpen the preview window by passing in file preview information. Repeated calls within 1 second are invalid
openPreviewEasyOpen the preview window through the uri of the file. Repeated calls within 1 second are invalid
canPreviewDetermine whether the file can be previewed based on the uri of the file
hasDisplayedDetermine whether the preview window already exists
closePreviewClose the preview window, only effective if the preview window exists
loadDataLoad preview file information. Only effective if the preview window exists
loadDataEasyLoad preview file information. Only effective if the preview window exists
onSharePreviewCall other app preview files
getTypeDescriptorGet TypeDescriptor (descriptive class for standardized data types)
getMimeTypeGet file mimeType according to file suffix name
getIconFileStrGet the icon of the corresponding file type according to the file suffix name

LocationUtil (positioning tool class (WGS-84 coordinate system))使用案例

MethodsIntroduction
isLocationEnabledDetermine whether the location service has been enabled (registered is enabled).
requestLocationPermissionsApply for positioning permissions
getCurrentLocationEasyGet current location
getCurrentLocationGet current location
getLastLocationGet the last location
onLocationChangeEasyEnable location change subscription and initiate positioning request.
onLocationChangeEnable location change subscription and initiate positioning request
offLocationChangeClose the location change subscription and delete the corresponding location request
onLocationErrorError codes during subscription continuous positioning
offLocationErrorError codes during unsubscribe to continuous positioning
onLocationEnabledChangeSubscription Location Service Status Change
offLocationEnabledChangeUnsubscribe to location service status changes
isGeocoderAvailableDetermine whether geocoding and inverse geocoding services are available
getAddressFromLocationNameGeocode, convert geographic description to specific coordinates
getGeoAddressFromLocationNameGeocode, converting geographic description into a specific coordinate set
getAddressFromLocationInverse geocoding, convert coordinates to geographic description
getGeoAddressFromLocationInverse geocoding, convert coordinates to geodescription collection
getCountryCodeGet the current country code
calculateDistanceCalculate the straight line distance between these two points in meters
calculateDistanceEasyCalculate the straight line distance between these two points based on the specified two latitude and longitude coordinate points, in meters
convertCoordinate
convertCoordinateSync
Coordinate conversion, convert WGS84 coordinate system to GCJ02 coordinate system
convertCoordinateEasyCoordinate conversion, convert WGS84 coordinate system to GCJ02 coordinate system
getErrorMsgGet positioning related error msg

LogUtil (log tool class)使用案例

MethodsIntroduction
initInitialize log parameters (this method is recommended to be called in Ability)
setDomainSet the domain identifier corresponding to the log, the range is 0x0~0xFFFF. (This method is recommended to be called in Ability)
setTagSet the log identifier (this method is recommended to be called in Ability)
setShowLogWhether to print the log (this method is recommended to be called in Ability)
setHilogLog printing method (this method is recommended to be called in Ability)
debugPrint DEBUG level log
infoPrint INFO level log
warnPrint WARN level log
errorPrint ERROR level log
fatalPrint FATAL level log
printPrint log, no borders.

CrashUtil (global exception capture, crash log collection)使用案例

MethodsIntroduction
onHandledRegister an error observer (this method is recommended to be called in Ability). After registration, you can capture the js crash generated by the application, and the process will not exit when the application crashes. Write exception information to local file
onDestroyLog out the error observer
isHandledDetermine whether the error observer exists
getFilePathGet the log file path (used to read exception files and export exception files)
accessDetermine whether the log file exists
deleteDelete log file
getExceptionJsonGet the JSON string for the exception log
getExceptionListGet collection of exception logs
enableAppRecoveryEnable the application recovery function and fill in the parameters in order. After this interface is called, the first Ability supports recovery when the application starts from the initiator.
restartAppRestart APP and pull up the first Ability when the application starts. You can use it with the errorManager related interface
saveAppStateSave the current App status or actively save the state of Ability, which will be used the next time you resume startup. It can be used with errorManager-related interface
setRestartWantSet the next time you restore the Ability in the scene actively pulling up. This Ability must be the UIAbility under the current package

EmitterUtil (Emitter tool class (for inter-thread communication))使用案例

MethodsIntroduction
postSend Event
onSubscribeSubscription Events
onceSubscribeSingle subscription specified event
unSubscribeUnsubscribe
getListenerCountGet the number of subscriptions for the specified event
onSubscribe to events, support Callback
oncesingle subscription to specified events, support Callback
offUnsubscribe to event, support Callback

WantUtil (Want tool class)使用案例

MethodsIntroduction
toSettingJump the system settings page (used with the URI constants in WantUtil to jump to more settings pages)
toAppSettingJump to App Settings Page
toNotificationSettingJump notification settings page
toNetworkSettingJump to the mobile network settings page
toWifiSettingJump to WLAN Settings Page
toBluetoothSettingJump Bluetooth Settings Page
toNfcSettingJump NFC Settings Page
toVolumeSettingJump sound and vibration settings page
toStorageSettingJump Storage Settings Page
toBatterySettingJump Battery Settings Page
toWebBrowserPull up the system browser
toAppGalleryDetailPull up the application details interface corresponding to the application market
toFileManagementPull up the system file manager
startMMSPull up the SMS interface and specify the contact person
openFileCall three-party software to open the file

KvUtil (key value database tool class)使用案例

MethodsIntroduction
putAdd key-value pairs of the specified type to the database
get
getString
getNumber
getBoolean
getUint8Array
Get the value of the specified key
deleteDelete data with specified key value from the database
putBatchBatch insert key-value pairs into SingleKVStore database
deleteBatchBatch delete key-value pairs in SingleKVStore database
getEntriesGet all key-value pairs that match the specified key prefix
backupBackup database with a specified name
restoreRestoreRecover database from specified database file
deleteBackupDelete backup file according to the specified name
onDataChangeSubscribe to data change notifications for specified types
offDataChangeUnsubscribe to data change notification

PreferencesUtil (Preferences tool class)使用案例

MethodsIntroduction
initInitialization
put
putSync
Cache data
get
getSync
Get cached value
getString
getStringSync
Get cached value of string type
getNumber
getNumberSync
Get cached value of type number
getBoolean
getBooleanSync
Get cached value of boolean type
has
hasSync
Check whether the cache instance contains the stored key-value pair for the given key
getBoolean
getBooleanSync
Get cached value of boolean type
delete
deleteSync
Delete cache value
clear
clearSync
Clear cache
deletePreferencesRemove the specified Preferences instance from the cache. If the Preferences instance has a corresponding persistent file, its persistent file will be deleted at the same time.
onChangeSubscribe to data change. After the value of the subscribed Key is changed, the callback callback is triggered after the flush method is executed
offChangeUnsubscribe to data changes
onDataChangeAccurate subscription data changes. Only after the subscribed key value changes, the callback callback is triggered after the flush method is executed
offDataChangeCancel the exact subscription data change

CacheUtil (cache tool class)使用案例

MethodsIntroduction
hasWhether the cached data exists
getGet the cached data
putSave data into cache
removeDelete the cache corresponding to the key
isEmptyDetermine whether the cache is empty
clearClear cached data

LRUCacheUtil (LRUCache Cache Tool Class)使用案例

MethodsIntroduction
getInstanceGet singleton of LRUCacheUtil
hasDetermine whether the cache corresponding to the key is included
getGet the cache corresponding to the key
putAdd cache to lruCache
removeDelete the cache corresponding to the key
isEmptyDetermine whether the lruCache cache is empty
getCapacityGet the capacity of the current buffer
updateCapacityReset the capacity of lruCache
clearClear cache data and reset lruCache size

NotificationUtil (notification tool class)使用案例

MethodsIntroduction
setDefaultConfigSet the default unified configuration for notifications
isNotificationEnabled
isNotificationEnabledSync
Query whether the notification is authorized
authorizeNotificationRequest notification authorization, and the first call will pop up the window for the user to choose.
isSupportTemplateCheck whether the template exists, currently only progress bar templates are supported.
isDistributedEnabledQuery whether the device supports distributed notifications
publishBasicPublish normal text notification
publishMultiLinePublish multi-text notification
publishLongTextPublish long text notification
publishPicturePublish notifications with pictures
publishTemplatePublish Template Notification
cancelcancel notice
cancelGroupCancel notifications under the specified group of this application
cancelAllCancel All Notifications
setBadgeSet the number of desktop angle marks
clearBadgeClear the corner marker on the desktop
setBadgeFromNotificationCountSet the number of desktop corner markers, from the number of notifications
getActiveNotificationCountGet the number of notifications that are not deleted by the current application
getActiveNotificationsGet the list of notifications that are not deleted by the current application
addSlotCreate a notification channel of a specified type
getSlotGet a notification channel of a specified type
getSlotsGet all notification channels for this application
removeSlotDelete notification channel of the type specified by this application
removeAllSlotsDelete all notification channels for this application
generateNotificationIdGenerate notification id (using timestamp as id)
getDefaultWantAgentCreate a Want that pulls up Ability
getCompressedPictureGet compressed notification image (the total number of bytes of image pixels cannot exceed 2MB)
getCompressedIconGet the compressed notification icon (the total number of bytes of the icon pixels does not exceed 192KB)

SnapshotUtil (component screenshot and window screenshot tool class)使用案例

MethodsIntroduction
get
getSync
Get screenshots of the loaded component, pass in the component id of the component, find the corresponding component to take screenshots
createFromBuilderRender CustomBuilder custom components in the application background and output their screenshots
snapshotGet window screenshot, use Promise asynchronous callback
onSnapshotListenerTurn on monitoring of system screenshot events
removeSnapshotListenerClose the monitoring of system screenshot events

KeyboardUtil (keyboard tool class)使用案例

MethodsIntroduction
showPull up the keyboard
hideHide keyboard
onKeyboardListenerSubscribe to input method soft keyboard to show and hide events
removeKeyboardListenerUnsubscribe to input method soft keyboard to show or hide events

PasteboardUtil (clipboard tool class)使用案例

MethodsIntroduction
requestPermissionsApply for clipboard permissions
getSystemPasteboardGet System Clipboard Object
hasData
hasDataSync
Determine whether there is any content in the system clipboard
setData
setDataSync
Write data to the system clipboard
getData
getDataSync
Read the system clipboard content
setDataText
setDataTextSync
Write plain text data to the system clipboard
getDataText
getDataTextSync
Read the plain text content of the system clipboard
setDataHtml
setDataHtmlSync
Write HTML data to the system clipboard
getDataHtml
getDataHtmlSync
Read system clipboard HTML content
setDataUri
setDataUriSync
Write URI data to the system clipboard
getDataUri
getDataUriSync
Read the URI content of the system clipboard
setDataWant
setDataWantSync
Write Want data to the system clipboard
getDataWant
getDataWantSync
Read the Want content of the system clipboard
setDataPixelMap
setDataPixelMapSync
Write PixelMap data to the system clipboard
getDataPixelMap
getDataPixelMapSync
Read the system clipboard PixelMap content
getDataStr
getDataStrSync
Read strings in the system clipboard
getDataEasyRead content in the system clipboard (plain text content, HTML content, URI content, Want content, PixelMap content)
clearData
clearDataSync
Clear system clipboard content

AssetUtil (key asset storage service tool class)使用案例

MethodsIntroduction
add
addSync
Add a key asset
get
getSync
Query key assets
remove
removeSync
Delete key assets
canIUseWhether the current device supports this module

ResUtil (resource tool class)使用案例

MethodsIntroduction
getResourceManagerGet the ability to provide access to application resources
getBooleanGet the boolean result corresponding to the specified resource
getBooleanByNameGet the boolean result corresponding to the specified resource name
getNumberGet the integer value or float value corresponding to the specified resource
getNumberByNameGet the integer value or float value corresponding to the specified resource name
getStringValue
getStringSync
Get the string corresponding to the specified resource
getStringByName
getStringByNameSync
Get the string corresponding to the specified resource name
getStringArrayValue
getStringArrayValueSync
Get the string array corresponding to the specified resource
getStringArrayByName
getStringArrayByNameSync
Get the string array corresponding to the specified resource name
getPluralStringValue
getPluralStringValueSync
Get a single-plural numeric string represented by the specified resource object based on the specified number
getPluralStringByName
getPluralStringByNameSync
Get a single-plural numeric string represented by the specified resource name based on the specified number
getColor
getColorSync
Get the color value corresponding to the specified resource (decimal)
getColorByName
getColorByNameSync
Get the color value corresponding to the specified resource name (decimal)
getMediaContent
getMediaContentSync
Get the default or specified screen density media file content corresponding to the specified resource
getMediaByName
getMediaByNameSync
Get the default or specified screen density media file content corresponding to the specified resource name
getMediaContentBase64
getMediaContentBase64Sync
Get the default or specified screen density picture resource Base64 encoding corresponding to the specified resource ID
getMediaBase64ByName
getMediaBase64ByNameSync
Get the default or specified screen density picture resource Base64 encoding corresponding to the specified resource name
getRawFileContent
getRawFileContentSync
Get the content of the corresponding rawfile file in the resources/rawfile directory
getRawFileContentStr
getRawFileContentStrSync
Get the content of the corresponding rawfile file in the resources/rawfile directory (string)
getRawFileList
getRawFileListSync
Get the folder and file list in the resources/rawfile directory (if there is no file in the folder, it will not be returned; if there is a file in the folder, it will return the folder and file list)
getRawFdUser obtains the descriptor information of the corresponding rawfile file in the resources/rawfile directory
closeRawFd
closeRawFdSync
User closes the descriptor information of the rawfile file in the resources/rawfile directory
addResourceWhen the application runs, load the specified resource path to achieve resource coverage
removeResourceWhen the user runs, remove the specified resource path and restore the resource before it was overwritten
isRawDirThe user determines whether the specified path is a directory under rawfile (true: means it is a directory under rawfile, false: means it is not a directory under rawfile)
getConfiguration
getConfigurationSync
Get the device's Configuration
getDeviceCapability
getDeviceCapabilitySync
Get DeviceCapability for DeviceCapability

ObjectUtil (Object Tool Class)使用案例

MethodsIntroduction
getHashGet the Hash value of the object
getClassNameGet the Class name of the object
getMethodsNamesGet all method names of the object
isStringDetermine whether it is a String
isNullDetermine whether the object is empty
isEmptyDetermine whether the attribute content is empty
shallowCopyshallowCopy
deepCopyDeep Copy Object
assignMerge two or more objects
objToClassobj to class to solve the problem of missing method after obj as class
deleteRecordDeleteElements in Record
getValueGet object value through key
setValueDynamically add or modify attributes to object obj

JSONUtil (JSON tool class)使用案例

MethodsIntroduction
jsonToBeanJSON string to object
beanToJsonStrObject to JSON string
jsonToArrayJSON string to Array
jsonToMapJSON string to Map
mapToJsonStrMap to JSON string
isJSONStrDetermine whether it is a string format json

DateUtil (date tool class)使用案例

MethodsIntroduction
getFormatDateGet the formatted date and format the incoming date as Date
getFormatDateStrGet the formatted date and format the incoming date into a string of the specified format
getTodayGet today's date
getTodayTimeGet the timestamp for today
getTodayStrGet the time of today, string type
isTodayDetermine whether the date is today
getNowYearGet the current year
getNowMonthGet the current month
getNowDayGet Current Day
isLeapYearDetermine whether it is a leap year
getDaysByYearGet the number of days in the specified year
getDaysByMonthGet the number of days in the specified month
isSameYearDetermine whether two dates are the same year
isSameMonthDetermine whether two dates are the same month
isSameWeekDetermine whether two dates are the same week
isSameDayDetermine whether it is the same day
isWeekendDetermine whether the specified date is a weekend in the calendar
compareDaysCompare the number of days when the specified date is different
compareDateCompare the number of milliseconds of the specified date
getAmountDayGet the date of the previous or the date of the next
getAmountDayStrGet the date of the previous few days or the date of the next few days, return the string
getBeforeDayGet the previous day date
getBeforeDayStrGet the date of the previous day, return the string
getAfterDayDay after obtain
getAfterDayStrGet the date after the day, return the string
getWeekOfMonthGet what week of the month a given date is
getWeekDayGet the given date is the day of the week
getLastDayOfMonthGet what day the last day of a given year and month
getFormatTimeFormat Time Date String (DateTimeFormat)
getFormatRangeFormat time date field string (DateTimeFormat)
getFormatRelativeTimeFormat Relative Time
getTipDateStrFormat timestamps to get prompt time strings

Base64Util (Base64 tool class)使用案例

MethodsIntroduction
decode
encodeSync
Decode, decode through input parameters and output corresponding Uint8Array object
encode
decodeSync
Encoding, output Uint8Array object after inputting parameters
encodeToStr
encodeToStrSync
Encode, output the corresponding text after inputting parameters

StrUtil (String tool class)使用案例

MethodsIntroduction
isNullDetermine whether the string is empty (undefined, null)
isNotNullDetermine whether the string is non-empty
isEmptyDetermine whether the string is empty (undefined, null, string length is 0)
isNotEmptyDetermine whether the string is non-empty
isBlankDetermine whether the string is empty and whitespace (whitespace includes spaces, tabs, full-width spaces and uninterrupted spaces)
isNotBlankDetermine whether the string is non-empty
trimRemove spaces at both ends of strings
trimAllRemove all spaces in string
replacereplace the matching regular in the string to the given string
replaceAllReplaceAllReplace all matching regulars in the string to the given string
startsWithDetermine whether a string starts with the given string
endsWithDetermine whether a string ends in the given string
repeatrepeat string number
toLowerConvert the entire string to lowercase
toUpperConvert the entire string to uppercase
capitalizeConvert the first letter of the string to uppercase, and the rest to lowercase
equalDetermine whether two incoming values ​​or strings are equal
notEqualDetermine whether two incoming values ​​or strings are not equal
strToUint8ArrayString to Uint8Array
unit8ArrayToStrUint8Array to string
strToBase64String to Base64 string
base64ToStrBase64 string to string
strToBufferString to ArrayBuffer
bufferToStrArrayBuffer to string
bufferToUint8ArrayArrayBuffer to Uint8Array
unit8ArrayToBufferUint8Array to ArrayBuffer
getErrorStrGet the JSON string of Error
getErrnoToStringGet detailed information corresponding to the system error code

CharUtil (character tool class)使用案例

MethodsIntroduction
isDigitDetermine whether the string char is a number
isLetterDetermine whether the string char is a letter
isLowerCaseDetermine whether the string char is a lowercase letter
isUpperCaseDetermine whether the string char is capital letter
isSpaceCharDetermine whether the string char is a space character
isWhitespaceDetermine whether the string char is a whitespace
isRTLDetermine whether the string char is a character from right to left language
isIdeographDetermine whether the string char is an ideographic text
isBlankCharDetermine whether there is a blank symbol. White space symbols include spaces, tab characters, full-width spaces and uninterrupted spaces
isAsciiDetermine whether the character is within the ASCII range (0~127)

NumberUtil (number tool class)使用案例

MethodsIntroduction
isNaNCheck if the value is NaN
isFiniteCheck if the value is a finite number
isIntegerCheck if the value is an integer
isSafeIntegerCheck if the value is a safe integer
isNumberDetermine whether it is a numerical value
isEvenCheck if the number is even
isOddCheck if the number is odd
toNumberConvert string to Number
toIntConvert string to integer
toFloatConvert string to floating point
averageCalculate the average of the numbers
addAdd
subsubtraction
sumsum
toDecimalConstruct Decimal
addDecimalAddition Decimal
subDecimalSubtraction Decimal
sumDecimalSumDecimal

ArrayUtil (collection tool class)使用案例

MethodsIntroduction
isNotEmptyDetermine whether a collection is a non-empty collection
isEmptyDetermine whether a set is an empty set
removeEmptyRemove empty values ​​from string array
trimRemoves the spaces before and after each value of the string array
distinctDeduplicate the array, and after deduplicate it, generate a new array, the original array remains unchanged
reverseInverting the array will modify the original array
filterArray filtering, filtering and returning required elements through filter function implementation
appendSplice data, use extension operators, and do not affect the original array.
minGet the minimum value of the array (value, string, date)
maxGet the maximum value of the array (value, string, date)
flattentiled 2D array
unionTile a 2D array and deduplicate
chunkArray chunking
containsDetermine whether the set contains a certain value
removeRemove a value from the collection

RandomUtil (random tool class)使用案例

MethodsIntroduction
getRandomBooleanGenerate random Boolean values ​​
getRandomIntGenerate random integers (the range can be specified)
getRandomNumberGenerate random numbers in a specified range
getRandomLimitGenerate random numbers in the specified range [0,limit)
getRandomChineseCharGenerate a random Chinese character
getRandomChineseGenerate random Chinese characters
getRandomStrRandomgenerates strings of specified length based on the specified string
getRandomDataBlobGenerate DataBlob of randomly specified length
getRandomUint8ArrayGenerate Uint8Array of randomly specified length
getRandomColorGenerate random colors, hexadecimal
generateUUID36Generate 36-bit UUID with -
generateUUID32Generate 32-bit UUID with -
generateRandomUUIDGenerate a random RFC 4122 version 4 string type UUID using Encrypted Secure Random Number Generator
generateRandomBinaryUUIDGenerate Random RFC 4122 Version 4 Uint8Array Type UUID using Encrypted Secure Random Number Generator

RegexUtil (regular tool class)使用案例

MethodsIntroduction
isMatchWhether the given content matches the regular (used with regular constants in RegexUtil)
isPhoneDetermine whether the incoming phone number is formatted correctly
isDigitsCheck if the string contains only numeric characters
isEmailDetermine whether the incoming email is formatted correctly
isEmojiDetermine whether a string contains emoticons
isValidCardVerify the validity of ID number

TypeUtil (Type Checking Tool Class)使用案例

MethodsIntroduction
isBooleanDetermine whether it is Boolean type
isNumberDetermine whether it is Number type
isStringDetermine whether it is String type
isObjectDetermine whether it is Object type
isArrayDetermine whether it is an array type
isResourceDetermine whether it is Resource type
isResourceStrDetermine whether it is ResourceStr type
isFunctionDetermine whether it is a function type
isMapCheck if it is Map type
isWeakMapCheck if it is WeakMap type
isSetCheck whether it is Set type
isWeakSetCheck if it is WeakSet type
isDateCheck if it is Date type
isArrayBufferCheck whether it is ArrayBuffer type
isSharedArrayBufferCheck if it is SharedArrayBuffer type
isAnyArrayBufferCheck if it is ArrayBuffer or SharedArrayBuffer type
isUint8ArrayCheck if it is a Uint8Array array type
isUint16ArrayCheck if it is a Uint16Array array type
isUint32ArrayCheck if it is a Uint32Array array type
isInt8ArrayCheck if it is an Int8Array array type
isInt16ArrayCheck if it is an Int16Array array type
isInt32ArrayCheck if it is an Int32Array array type
isTypedArrayCheck if it is TypedArray
isAsyncFunctionCheck if it is an asynchronous function type
isPromiseCheck if it is a Promise type
isProxyCheck if it is Proxy type
isRegExpCheck if it is RegExp type
isDataViewCheck if it is DataView type
isExternalCheck if it is native External type
isNativeErrorCheck if it is Error type

FormatUtil (format tool class)使用案例

MethodsIntroduction
isPhoneDetermine whether the incoming phone number is formatted correctly
getPhoneFormatFormat phone numbers
getPhoneLocationNameGet phone number home
transliteratorConvert input string from source format to target format (convert Chinese characters to pinyin)
getFormatPercentageFormat percentage to convert numbers from percentage string
getFormatPhoneFormat mobile phone number, hide the four middle digits
getFormatCardNoFormat ID number, hide the middle part number
getFormatFileSizeFormat file size
getTruncateTextShorten the long text, the excess is represented by an ellipsis
getIconFontparse iconFont characters
getQueryValueGet the parameters in the url, the value corresponding to the Key
getParamsUrlSplice parameters on the url and return the new url

ClickUtil (throttling, anti-shake tool category)使用案例

MethodsIntroduction
throttleThrottle: Only trigger once within a certain period of time
debounceAnti-shake: within a certain period of time, only the last operation will be executed, and the function will be executed after waiting milliseconds

TempUtil (temperature conversion tool class)使用案例

MethodsIntroduction
C2Fdegrees Celsius to degrees Fahrenheit
F2CFahrenheit to Celsius
C2KCelsius to Kelvin
K2CKelvin to Celsius
F2KFahrenheit to Kelvin
K2FKelvin to Fahrenheit

DialogUtil (pop-up tool class)使用案例

MethodsIntroduction
setDefaultConfigSet default uniform style
showConfirmDialogShow pop-up window (a button)
showPrimaryDialogShow pop-up window (two buttons)
showDialogDisplay pop-up window (multiple buttons)
showActionSheetList selection pop-up
showCalendarPickerCalendar Selector Popup
showDatePickerDate Sliding Selector Popup
showTimePickerTime Sliding Selector Popup
showTextPickerText Sliding Selector Popup

ToastUtil (toast tool class)使用案例

MethodsIntroduction
setDefaultConfigSet default uniform style
showToastPop up toast, default duration is 2s
showShortPop up short toast, default duration is: 1.5s
showLongPop up long toast, default duration is: 10s

SM2 (SM2 encryption and decryption)使用案例

MethodsIntroduction
encrypt
encryptSync
Encrypt
decrypt
decryptSync
Decrypt
generateKeyPair
generateKeyPairSync
GenerateKeyPairKeyPair
getConvertKeyPair
getConvertKeyPairSync
Get the converted asymmetric key KeyPair
getSM2PubKeyGet the convert SM2 public key, convert the SM2 public key in C1C2C3 format to the ASN.1 format required by Hongmeng
getSM2PriKeyGet Convert SM2 Private Key
getCipherTextSpecGet convert SM2 ciphertext format, ASN.1 format to C1C2C3 or C1C3C2
sign
signSync
Sign data
verify
verifySync
Verify the data
signSegment
signSegmentSync
SegmentSync
verifySegment
verifySegmentSync
Perform segment verification of data

SM3 (SM3 tool class)使用案例

MethodsIntroduction
digest
digestSync
SM3 Summary
digestSegment
digestSegmentSync
SM3 segment summary
hmac
hmacSync
SM3 message authentication code calculation
hmacSegment
hmacSegmentSync
SM3 message authentication code calculation, segmentation

SM4 (SM4 encryption and decryption)使用案例

MethodsIntroduction
encrypt
encryptSync
Encrypt
decrypt
decryptSync
Decrypt
encryptGCM
encryptGCMSync
Encrypt (GCM mode)
decryptGCM
decryptGCMSync
Decrypt (GCM mode)
encryptCBC
encryptCBCSync
Encrypt (CBC mode)
decryptCBC
decryptCBCSync
Decrypt (CBC mode)
encryptECB
encryptECBSync
Encrypt (ECB mode)
decryptECB
decryptECBSync
Decrypt (ECB mode)
encryptGCMSegment
encryptGCMSegmentSync
Encrypt (GCM mode) segmentation
decryptGCMSegment
decryptGCMSegmentSync
Decrypt (GCM mode) segmentation
generateSymKey
generateSymKeySync
Generate SymKey

AES (AES encryption and decryption)使用案例

MethodsIntroduction
encrypt
encryptSync
Encrypt
decrypt
decryptSync
Decrypt
encryptGCM
encryptGCMSync
Encrypt (GCM mode)
decryptGCM
decryptGCMSync
Decrypt (GCM mode)
encryptCBC
encryptCBCSync
Encrypt (CBC mode)
decryptCBC
decryptCBCSync
Decrypt (CBC mode)
encryptECB
encryptECBSync
Encrypt (ECB mode)
decryptECB
decryptECBSync
Decrypt (ECB mode)
encryptGCMSegment
encryptGCMSegmentSync
Encrypt (GCM mode) segmentation
decryptGCMSegment
decryptGCMSegmentSync
Decrypt (GCM mode) segmentation
generateSymKey
generateSymKeySync
Generate SymKey

DES (DES encryption and decryption)使用案例

MethodsIntroduction
encrypt
encryptSync
Encrypt
decrypt
decryptSync
Decrypt
encryptECB
encryptECBSync
Encrypt (ECB mode)
decryptECB
decryptECBSync
Decrypt (ECB mode)
encryptCBC
encryptCBCSync
Encrypt (CBC mode)
decryptCBC
decryptCBCSync
Decrypt (CBC mode)
generateSymKey
generateSymKeySync
Generate SymKey

RSA (RSA encryption and decryption)使用案例

MethodsIntroduction
encrypt
encryptSync
Encrypt
decrypt
decryptSync
Decrypt
encryptSegment
encryptSegmentSync
Encrypt, segmentation
decryptSegment
decryptSegmentSync
Decrypt, segmentation
generateKeyPair
generateKeyPairSync
GenerateKeyPairKeyPair
getConvertKeyPair
getConvertKeyPairSync
Get the converted asymmetric key KeyPair
sign
signSync
Sign data
verify
verifySync
Verify the data
signSegment
signSegmentSync
SegmentSync
verifySegment
verifySegmentSync
Perform segment verification of data
recover
recoverSync
Sign the data and restore the original data, currently only RSA supports

MD5 (MD5 tool class)使用案例

MethodsIntroduction
digest
digestSync
MD5 Summary
digestSegment
digestSegmentSync
MD5 abstract, segmentation
hmac
hmacSync
Message authentication code calculation
hmacSegment
hmacSegmentSync
Message authentication code calculation, segmentation

SHA (SHA tool class)使用案例

MethodsIntroduction
digest
digestSync
SHA Summary
digestSegment
digestSegmentSync
SHA abstract, segmentation
hmac
hmacSync
Message authentication code calculation
hmacSegment
hmacSegmentSync
Message authentication code calculation, segmentation

ECDSA (ECDSA tool class)使用案例

MethodsIntroduction
sign
signSync
Sign data
verify
verifySync
Verify the data
signSegment
signSegmentSync
SegmentSync
verifySegment
verifySegmentSync
Perform segment verification of data

CryptoUtil (encryption and decryption utility class, used with each encryption module)

MethodsIntroduction
encrypt
encryptSync
Encrypt
decrypt
decryptSync
Decrypt
generateSymKey
generateSymKeySync
Generate SymKey
getConvertSymKey
getConvertSymKeySync
Get the converted symmetric key SymKey
generateKeyPair
generateKeyPairSync
GenerateKeyPairKeyPair
getConvertKeyPair
getConvertKeyPairSync
Get the converted asymmetric key KeyPair
getPemKeyPairGet the specified data to generate an asymmetric key
generateIvParamsSpecGenerate IvParamsSpec
getIvParamsSpecGet Convert IvParamsSpec
generateGcmParamsSpecGenerateGcmParamsSpec
getGcmParamsSpecGet Convert GcmParamsSpec
sign
signSync
Sign data
verify
verifySync
Verify the data
signSegment
signSegmentSync
SegmentSync
verifySegment
verifySegmentSync
Perform segment verification of data
dynamicKey
dynamicKeySync
Key Negotiation
digest
digestSync
Abstract
digestSegment
digestSegmentSync
Abstract, segmentation
hmac
hmacSync
Message authentication code calculation
hmacSegment
hmacSegmentSync
Message authentication code calculation, segmentation

CryptoHelper (encrypted and decrypted data type conversion, used with each encryption module)

MethodsIntroduction
strToDataBlobString to DataBlob
dataBlobToStrDataBlob to String
strToUint8ArrayString to Uint8Array
uint8ArrayToStrUint8Array to String
getSymKeyDataBlobGet the key of type DataBlob
getKeyDataBlobGet the public or private key of type DataBlob
getRandomUint8ArrayGenerate random Uint8Array based on the incoming size
getUint8ArrayPaddingZeroUint8Array Zero Operation
toHexWithPaddingZeroZero Compensation Operation
stringToHexstring to Hex string
uint8ArrayToStringBytes to Understandable String

PickerUtil (photographing, file selection and saving, tool class)拆分至 picker_utils

MethodsIntroduction
camera
cameraEasy
Call the system camera, take photos, record videos
selectPhotoPull up the photoPicker interface by selecting mode, users can select one or more pictures/videos
savePhotoPull up photoPicker in the save mode to save the file name of the picture or video resource. If there are no parameters, the user needs to enter it by default
selectDocumentPull up the documentPicker interface by selecting mode, users can select one or more files
saveDocumentPull up the documentPicker interface through the save mode, and users can save one or more files
selectAudioPull up the audioPicker interface by selecting mode, users can select one or more audio files
saveAudioPull up the audioPicker interface through save mode, and users can save one or more audio files
MethodsIntroduction
select
selectEasy
Pull up the photoPicker interface by selecting mode, users can select one or more pictures/videos
saveApply for permission to save pictures or videos to the album.
showAssetsCreationDialogPop-up window authorization save, call the interface to pull up the save confirmation pop-up window.
showAssetsCreationDialogEasyPop-up window authorization save, call the interface to pull up the save confirmation pop-up window, and save.
applyChangesSave security controls, submit media change requests, insert pictures/videos.
getPhotoAssetGet the PhotoAsset object of the corresponding uri, used to read file information

ScanUtil (code tool class (scan code, code image generation, picture identification))拆分至 picker_utils

MethodsIntroduction
startScanForResultCall the default interface to scan the code and use the Promise method to asynchronously return the decoding result
generateBarcodeCode diagram generation, use Promise to return the generated code diagram asynchronously
decodeCall picture identification and use Promise to return the identification result asynchronously
decodeImageCall image data identification capability, use Promise asynchronous callback to return code identification results
onPickerScanForResultPull up the gallery through picker and select the picture, and call the picture identification code
canIUseScanDetermine whether the current device supports code capabilities

🍎Contribution code and technology communication

Any problems found during use can be askedIssueGive us; Of course, we also welcome you to send us a messagePR

https://gitee.com/tongyuyan/harmony-utils
https://github.com/787107497

🌏Open Source Protocol

This project is based onApache License 2.0, when copying and borrowing codes, please be sure to indicate the source.

0
Subscribe to my newsletter

Read articles from 桃花镇童长老 directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

桃花镇童长老
桃花镇童长老