DEV Community

Cover image for HarmonyOS Development: Those Common Resource Management Methods
程序员一鸣
程序员一鸣

Posted on

HarmonyOS Development: Those Common Resource Management Methods

Foreword 

this article is based on Api13 

in actual development, we often use resource management, such as obtaining the common device type, obtaining the screen direction, obtaining the screen density, etc. In addition, we often use to obtain the content that the resource has been configured, such as strings, such as pictures, such as array resources, which are common in the parameters that the specified type does not support the resource type. 

Under normal circumstances, the resources that we have configured in resources can be directly obtained, for example, the following cases:

 

{
"name": "test_string",
'value': 'A simple test data'
}
Enter fullscreen mode Exit fullscreen mode

then, in the code, we can get it directly through $r():

 

Text($r("app.string.test_string"))
Enter fullscreen mode Exit fullscreen mode

we can get it directly like this, because $r() returns Resource, and the content of the Text component also supports Resource. 

The $r() source code is as follows:

 

/**
 * global $r function
 *
 * @param { string } value
 * @param { any[] } params
 * @returns { Resource }
 * @syscap SystemCapability.ArkUI.ArkUI.Full
 * @crossplatform
 * @form
 * @atomicservice
 * @since 11
 */
declare function $r(value: string, ...params: any[]): Resource;
Enter fullscreen mode Exit fullscreen mode

the Text component source code is as follows:

 

 /**
     * Called when writing text.
     *
     * @param { string | Resource } content
     * @param { TextOptions } value
     * @returns { TextAttribute }
     * @syscap SystemCapability.ArkUI.ArkUI.Full
     * @crossplatform
     * @form
     * @atomicservice
     * @since 11
     */
    (content?: string | Resource, value?: TextOptions): TextAttribute;
Enter fullscreen mode Exit fullscreen mode

then the question arises, what if the component does not support Resource? Obviously, $r() cannot be used directly in this case. Some friends said that if they don't support it, they don't need to write it directly. Alas, if they write it directly, there is no problem. For projects written by themselves or without specifications, you can be reckless, but under projects with strict specifications, code reuse will be lost, in the case of changing text in the future, the cost will rise sharply, especially for those internationalized projects, so the content of a unified resource output can effectively avoid string hard coding and improve the maintainability, readability and internationalization of the code. 

For components that do not support Resource type parameters, we can use the method in Resource management to specify the acquisition, or the above code, we can directly use getStringSync to obtain.

Text(getContext().resourceManager.getStringSync($r("app.string.test_string").id))
Enter fullscreen mode Exit fullscreen mode

It should be noted that those that can be obtained with $r() can be used, and resource management can be used when they cannot be used. Through investigation, most text components support $r(), while only a few do not, such as ticker component, Search component, rich text RichText component, etc. 

Resource management in addition to the acquisition of strings, there are many can be obtained, such as arrays, such as pictures, etc., so for some constant attributes, we can define to the resources, through resource management to specify the acquisition, the following is a look at the common methods in resource management. 

I. Ways of Use 

through the context, we can directly get the resourceManager. If you are in the UI component, you can directly get it as follows:

 

let rManager = getContext().resourceManager
Enter fullscreen mode Exit fullscreen mode

II. Acquisition device screen orientation 

to determine the direction of the screen, you can use the direction attribute. There are two values: 0 and 1,0 is a vertical screen, 1 is a horizontal screen, or you can use the enumeration values DIRECTION_VERTICAL and DIRECTION_HORIZONTAL. The basic code is as follows:

 

let rManager = getContext().resourceManager
let direction = rManager.getConfigurationSync().direction
if(direction == resourceManager.Direction.DIRECTION_VERTICAL){
Console.log ("===Vertical Screen")
}else if(direction == resourceManager.Direction.DIRECTION_HORIZONTAL){
Console.log ("===landscape")
}
Enter fullscreen mode Exit fullscreen mode

III. Acquisition device Type 

get the device type, you can use the deviceType property, there are seven values to choose from. 

The basic code is as follows:

 

let rManager = getContext().resourceManager
let deviceType = rManager.getConfigurationSync().deviceType
if(deviceType == resourceManager.DeviceType.DEVICE_TYPE_PHONE){
Console.log ("===phone")
}else if(deviceType == resourceManager.DeviceType.DEVICE_TYPE_TABLET){
Console.log ("===tablet")
}else if(deviceType == resourceManager.DeviceType.DEVICE_TYPE_CAR){
Console.log ("===car")
}else if(deviceType == resourceManager.DeviceType.DEVICE_TYPE_PC){
Console.log ("===Computer")
}else if(deviceType == resourceManager.DeviceType.DEVICE_TYPE_TV){
Console.log ("===TV")
}else if(deviceType == resourceManager.DeviceType.DEVICE_TYPE_WEARABLE){
Console.log ("===Wear")
}else if(deviceType == resourceManager.DeviceType.DEVICE_TYPE_2IN1){
console.log("===2IN1")
}
Enter fullscreen mode Exit fullscreen mode

IV. Acquisition device Screen Density 

the screen density is obtained through the screenDensity attribute. There are 6 types to choose from, ranging from small density to super high density. The basic code is as follows:

 

let rManager = getContext().resourceManager
let screenDensity = rManager.getConfigurationSync().screenDensity
if(screenDensity == resourceManager.ScreenDensity.SCREEN_SDPI){
Console.log ("===Small screen density")
}else if(screenDensity == resourceManager.ScreenDensity.SCREEN_MDPI){
Console.log (===Medium screen density)
}else if(screenDensity == resourceManager.ScreenDensity.SCREEN_LDPI){
Console.log (===Large scale screen density)
}else if(screenDensity == resourceManager.ScreenDensity.SCREEN_XLDPI){
Console.log ("==Extra Large Screen Density")
}else if(screenDensity == resourceManager.ScreenDensity.SCREEN_XXLDPI){
Console.log ("==Super Large Screen Density")
}else if(screenDensity == resourceManager.ScreenDensity.SCREEN_XXXLDPI){
Console.log ("==Ultra Large Screen Density")
}
Enter fullscreen mode Exit fullscreen mode

v. AcquisitionColor mode 

the color mode is obtained by colorMode. There are two values, DARK color mode and LIGHT color mode, that is, 0 and 1 represent. Similarly, it can also be judged by enumerating values, DARK and LIGHT.

 

let rManager = getContext().resourceManager
let colorMode = rManager.getConfigurationSync().colorMode
if(colorMode == resourceManager.ColorMode.DARK){
Console.log (===Dark Mode)
}else if(colorMode == resourceManager.ColorMode.LIGHT){
Console.log ("===Light Mode")
}
Enter fullscreen mode Exit fullscreen mode

Six, get string resources 

this has already been the case in the foreword, which can be passed. getStringSync method to get take, supports multiple methods, such as only passing Resource, the code is as follows:

 

  let rManager = getContext().resourceManager
  let testString = rManager.getStringSync($r("app.string.test_string"))
  console.log("==="+testString)
Enter fullscreen mode Exit fullscreen mode

of course, it also supports obtaining the string corresponding to the specified resource ID, which is the same as in the foreword. Of course, it also supports formatting parameters. 

Formatting parameters 

define formatting parameters:

 

{
"name": "test_string",
'value': 'A simple% d test data'
}
Enter fullscreen mode Exit fullscreen mode

the code is called as follows:

 

let rManager = getContext().resourceManager
    let testString = rManager.getStringSync($r("app.string.test_string").id,100)
    console.log("==="+testString)
Enter fullscreen mode Exit fullscreen mode

print as follows:

 

===A simple 100 test data
Enter fullscreen mode Exit fullscreen mode

format string resource parameters. Supported parameter types:%d,% f,% s,%%,% numeric $d,% numeric $f,% numeric $s. 

Get by defining name 

the above acquisition method requires $r() to assist in acquisition. There is also a relatively simple way to obtain it directly through the defined name, which is through get it through the getStringByNameSync method, which also supports formatting parameters.

 

let rManager = getContext().resourceManager
let testString = rManager.getStringByNameSync("test_string")
console.log("==="+testString)
Enter fullscreen mode Exit fullscreen mode

By getStringValue 

we can also passThe getStringValue method is used to obtain the defined resources. There are two methods: callback asynchronous callback and Promise asynchronous callback. It also supports resource and resource id acquisition. 

callback Asynchronous callback

let rManager = getContext().resourceManager
    rManager.getStringValue($r("app.string.test_string").id, (err,testString) => {
      console.log("===" + testString)
    })
Enter fullscreen mode Exit fullscreen mode

Promise asynchronous callback


let testString=await rManager.getStringValue($r("app.string.test_string"))
console.log("===" + testString)
Enter fullscreen mode Exit fullscreen mode

obtain by getStringByName 

there are also two ways to get it, callback asynchronous callback and Promise asynchronous callback can also be obtained in the form of resource and resource id. The following is a simple example.

 

let rManager = getContext().resourceManager
let testString=await rManager.getStringByName("test_string")
console.log("===" + testString)
Enter fullscreen mode Exit fullscreen mode

Seven, get string array resources 

there are four methods to obtain, namely getStringArrayValue,getStringArrayByName,getStringArrayValueSync. 

getStringArrayValueSync. 

getStringArrayValue 

getStringArrayValue supports resource and id forms. Similarly, there are two ways to obtain it respectively callback asynchronous callback and Promise asynchronous callback. 

callback Asynchronous callback

 

let rManager = getContext().resourceManager
   rManager.getStringArrayValue($r("app.strarray.test"),(err,data)=>{
      console.log("===" + data)
    })
Enter fullscreen mode Exit fullscreen mode

Promise asynchronous callback

 

let data= await rManager.getStringArrayValue($r("app.strarray.test"))
console.log("===" + data)
Enter fullscreen mode Exit fullscreen mode

the above methods all support the form of id, so I won't repeat them here. 

getStringArrayByName

getStringArrayByName supports resource and id formats. Similarly, there are also two ways to obtain callback asynchronous callback and Promise asynchronous callback. 

callback Asynchronous callback

 

let rManager = getContext().resourceManager
    rManager.getStringArrayByName("test", (err, data) => {
      console.log("===" + data)
    })
Enter fullscreen mode Exit fullscreen mode

Promise asynchronous callback

 

let rManager = getContext().resourceManager
let data= await rManager.getStringArrayByName("test")
console.log("===" + data)
Enter fullscreen mode Exit fullscreen mode

getStringArrayValueSync and getStringArrayValueSync are both synchronized and support the form of id and resource. The basic usage is the same, but I will not go into details. 

VIII. Acquisition number of resources 

number is similar to a string, except that the method name is different. Two acquisition methods are provided, getNumber and getNumberByName, which are used to obtain the integer value or float value corresponding to the specified resource ID. 

getNumber

supports Resource and Resource ID.

 

let rManager = getContext().resourceManager
let integer_1 = rManager.getNumber($r("app.integer.integer_1"))
console.log("==="+integer_1)
Enter fullscreen mode Exit fullscreen mode

getNumberByName

only one method is supported, that is, obtaining by the defined name.

 

let rManager = getContext().resourceManager
let integer_1 = rManager.getNumberByName("integer_1")
console.log("==="+integer_1)
Enter fullscreen mode Exit fullscreen mode

IX. Acquiring a boolean resources 

usage and number are basically the same. 

getBoolean

    let rManager = getContext().resourceManager
    let boolean_1 = rManager.getBoolean($r("app.boolean.boolean_1"))
    console.log("===" + boolean_1)
Enter fullscreen mode Exit fullscreen mode

getBooleanByName

let rManager = getContext().resourceManager
    let boolean_1 = rManager.getBooleanByName("boolean_1")
    console.log("===" + boolean_1)
Enter fullscreen mode Exit fullscreen mode

x. Access to other resources

As long as the resources are defined in resources, we can obtain them, such as colors, audio and video, pictures, etc., through resourceManager. For example, colors can be obtained through getColor, getColorSync, getColorByName, and getColorByNameSync. There are too many contents. Please introduce them later. 

Related Summary 

skilled use of resource management can greatly improve our development efficiency, not only in some components, but also in some three-party sdk. Due to the single type of definition, the use of resource management is also very common for project maintenance. 

Article label: HarmonyOS/ArkUI/resource management

Top comments (0)