介紹
本工程使用[@ohos.app.ability.common] 接口中的AbilityContext類,獲取資源管理器resourceManager,使用[@ohos.resourceManager.d.ts]中的接口,展示了格式化字符串查詢、基于指定屏幕分辨率查詢媒體資源、獲取系統(tǒng)資源管理對象等基礎(chǔ)功能,以及展示了資源靜態(tài)overlay以及運行時overlay的特性功能。
效果預覽
使用說明
此界面為主頁面,其中展示了資源管理API各類接口的調(diào)用以及特性Overlay場景功能。其作用有:
1、點擊資源API調(diào)用示例按鈕,可跳轉(zhuǎn)到資源API示例頁面
2、點擊Overlay使用示例,可以跳轉(zhuǎn)到Overlay的使用示例界面。
資源API調(diào)用示例
使用說明
此頁面展示了當前資源管理接口的調(diào)用以及接口對應的返回結(jié)果。
靜態(tài)overlay場景
使用說明
此頁面展示靜態(tài)overlay功能,功能使用如下:
1、靜態(tài)overlay是默認使能的,當前顯示的是靜態(tài)overlay中的字符串和圖標。
2、點擊Disable可以觸發(fā)去使能,重啟應用可以恢復顯示應用的字符串和圖標。
3、點擊enable可以觸發(fā)使能,重啟應用可以再次顯示overlay中的字符串和圖標。
源碼參考:[Overlay示例]在最下面
運行時overlay場景
使用說明
此頁面展示運行時overlay功能,功能使用如下:
1、點擊addResource可以觸發(fā)運行時overlay,此時會使用運行時overlay中的資源覆蓋之前的字符串和圖標。
2、點擊removeResource可以觸發(fā)移除運行時overlay,此時會移除運行時overlay,恢復到覆蓋前的字符串和圖標。
具體實現(xiàn)
資源API調(diào)用示例具體實現(xiàn):
1、使用getContext()接口獲取context對象,使用context.resourceManager獲取資源管理對象,然后調(diào)用resourceManager內(nèi)部的相關(guān)接口獲取對應資源,例如:
- 獲取字符串資源:resourceManager.getStringValue()
- 獲取字符串數(shù)組資源:resourceManager.getStringArrayValue()
- 獲取圖片資源:resourceManager.getMediaContent()
- 獲取格式化字符串資源:resourceManager.getStringSync()
- 獲取指定屏幕分辨率媒體資源:resourceManager.getMediaContentBase64()
2、導包resourceManager,使用resourceManager.getSystemResourceManager()獲取系統(tǒng)資源管理對象,然后獲取系統(tǒng)資源。 |
源碼參考:[資源API調(diào)用示例]
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import resourceManager from '@ohos.resourceManager';
import hilog from '@ohos.hilog';
import { BusinessError } from '@ohos.base';
const TAG = '[Sample_ResourceManager]';
const DOMAIN = 0xFF00;
const SPECIFIED_NUM = 2;
let resMgr = getContext().resourceManager;
async function getString(resId: number): Promise< string | undefined > {
try {
let value = await resMgr.getStringValue(resId);
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getStringValue failed, error code: ${code}, message: ${message}.`);
return;
}
}
async function getStringArray(resource: resourceManager.Resource): Promise< Array< string > | undefined > {
try {
let value = await resMgr.getStringArrayValue(resource);
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getStringArrayValue failed, error code: ${code}, message: ${message}.`);
return;
}
}
async function getPluralString(resId: number, num: number): Promise< string | undefined > {
try {
let value = await resMgr.getPluralStringValue(resId, num);
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getPluralStringValue failed, error code: ${code}, message: ${message}.`);
return;
}
}
async function getDeviceCapability(): Promise< resourceManager.DeviceCapability | undefined > {
try {
let value = await resMgr.getDeviceCapability();
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getDeviceCapability failed, error code: ${code}, message: ${message}.`);
return;
}
}
async function getConfiguration(): Promise< resourceManager.Configuration | undefined > {
try {
let value = await resMgr.getConfiguration();
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getConfiguration failed, error code: ${code}, message: ${message}.`);
return;
}
}
async function getMedia(resId: number): Promise< Uint8Array | undefined > {
try {
let value = await resMgr.getMediaContent(resId);
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getMediaContent failed, error code: ${code}, message: ${message}.`);
return;
}
}
async function getMediaBase64(resId: number): Promise< string | undefined > {
try {
let value = await resMgr.getMediaContentBase64(resId);
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getMediaContentBase64 failed, error code: ${code}, message: ${message}.`);
return;
}
}
function getFormatString(resId: number, world: string): string | undefined {
try {
let value = resMgr.getStringSync(resId, world);
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getStringSync failed, error code: ${code}, message: ${message}.`);
return;
}
}
async function getDensityMediaBase64(resId: number, density: number): Promise< string | undefined > {
try {
let value = await resMgr.getMediaContentBase64(resId, density);
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getDensityMediaBase64 failed, error code: ${code}, message: ${message}.`);
return;
}
}
async function getSystemMediaBase64(resId: number): Promise< string | undefined > {
// 獲取僅系統(tǒng)資源管理對象
let sysMgr = resourceManager.getSystemResourceManager();
try {
let value = await sysMgr.getMediaContentBase64(resId);
return value;
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
hilog.error(DOMAIN, TAG, `getMediaContentBase64 failed, error code: ${code}, message: ${message}.`);
return;
}
}
@Entry
@Component
struct Index {
@State string_str: string = 'string'
@State strArray: string = 'stringArray'
@State plural: string = 'plural'
@State configuration: string = 'configuration'
@State capability: string = 'capability'
@State media: string = 'media'
@State mediaBase: string = 'mediaBase'
@State formatStr: string = 'Format String'
@State densityMedia: string = 'Density Media'
@State systemRes: string = 'System Res'
async aboutToAppear() {
this.string_str = await getString($r('app.string.string_str').id) as string;
let resource: resourceManager.Resource = {
bundleName: "ohos.samples.resourcemanager",
moduleName: "entry",
id: $r('app.strarray.str_array').id
}
this.strArray = JSON.stringify(await getStringArray(resource) as Array< string >);
this.plural = await getPluralString($r('app.plural.eat_apple').id, SPECIFIED_NUM) as string;
this.configuration = JSON.stringify(await getConfiguration() as resourceManager.Configuration);
this.capability = JSON.stringify(await getDeviceCapability() as resourceManager.DeviceCapability);
this.media = JSON.stringify(((await getMedia($r('app.media.app_icon').id)) as Uint8Array).length);
this.mediaBase = JSON.stringify(((await getMediaBase64($r('app.media.app_icon').id)) as string).length);
this.formatStr = getFormatString($r('app.string.formatStr').id,
await getString($r('app.string.world').id) as string) as string;
this.densityMedia = await getDensityMediaBase64($r('app.media.density').id, 640) as string;
this.systemRes = await getSystemMediaBase64($r('sys.media.ohos_app_icon').id) as string;
}
build() {
Column() {
Text($r('app.string.title'))
.width('100%')
.height(50)
.backgroundColor($r('app.color.text_color'))
.fontColor(Color.White)
.fontSize(20)
.padding({ left: 15 })
Scroll() {
Column() {
Text($r('app.string.stringDesc'))
.fontSize(25)
Text(this.string_str)
.fontSize(25)
.fontColor('#ffff0000')
.fontWeight(FontWeight.Bold)
Text($r('app.string.stringArrayDesc'))
.fontSize(25)
Text(this.strArray)
.fontSize(25)
.fontColor('#ffff0000')
.fontWeight(FontWeight.Bold)
Text($r('app.string.pluralStringDesc'))
.fontSize(25)
Text(this.plural)
.fontSize(25)
.fontColor('#ffff0000')
.fontWeight(FontWeight.Bold)
Text($r('app.string.configurationDesc'))
.fontSize(25)
Text(this.configuration)
.fontSize(25)
.fontColor('#ffff0000')
.fontWeight(FontWeight.Bold)
Text($r('app.string.capabilityDesc'))
.fontSize(25)
Text(this.capability)
.fontSize(25)
.fontColor('#ffff0000')
.fontWeight(FontWeight.Bold)
Text($r('app.string.mediaDesc'))
.fontSize(25)
Text(this.media)
.fontSize(25)
.fontColor('#ffff0000')
.fontWeight(FontWeight.Bold)
Text($r('app.string.mediaBase64Desc'))
.fontSize(25)
Text(this.mediaBase)
.fontSize(25)
.fontColor('#ffff0000')
.fontWeight(FontWeight.Bold)
Text($r('app.string.formatStrDesc'))
.fontSize(25)
Text(this.formatStr)
.fontSize(25)
.fontColor('#ffff0000')
.fontWeight(FontWeight.Bold)
Text($r('app.string.densityMediaDesc'))
.fontSize(25)
Image(this.densityMedia)
.id('getDensityMedia')
.height('10%')
Text($r('app.string.systemResDesc'))
.fontSize(25)
Image(this.systemRes)
.id('getSystemMedia')
.height('10%')
}
.width('100%')
.padding(10)
.alignItems(HorizontalAlign.Start)
}
}
.width('100%')
.height('100%')
}
}
overlay場景的具體實現(xiàn):
1、靜態(tài)overlay主要是通過加載overly中的資源實現(xiàn)資源覆蓋,需要在對應的module.json中添加"targetModuleName":"entry", 表示覆蓋entry中的資源,默認使能,也可調(diào)用包管理接口進行使能和去使能。
使用步驟為:在安裝完entry的hap后,需要把library模塊生成的library-default-signed.hsp推送到/data/test下,使用bm install命令進行安裝。
腳本語言如下:
hdc_std shell mount -o remount,rw /
hdc_std install ./entry-default-signed.hap
hdc_std shell mkdir /data/test
hdc_std file send ./libraryOverlay-default-signed.hsp /data/test
hdc_std shell bm install -p "/data/test/libraryOverlay-default-signed.hsp"
pause
2、運行時overlay資源加載,主要是在應用運行過程中實現(xiàn)資源的覆蓋,需要應用主動調(diào)用資源的addResource接口實現(xiàn)資源的覆蓋以及資源的移除,此功能不持久化。
使用步驟為: 在安裝完entry的hap后,需要把libraryRuntimeOverlay模塊生成的libraryRuntimeOverlay-default-signed.hsp推送到應用對應的安裝目錄下。
腳本語言如下:
hdc_std shell mount -o remount,rw /
hdc_std install ./entry-default-signed.hap
hdc_std file send ./libraryRuntimeOverlay-default-signed.hsp /data/app/el1/bundle/public/ohos.samples.resourcemanager
pause
源碼參考:[Overlay示例]
/*
* Copyright (c) 2023 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import overlay from '@ohos.bundle.overlay';
import { BusinessError } from '@ohos.base';
@Entry
@Component
struct Overlay {
private resmgr = getContext().resourceManager;
@State message: string = 'Test Overlay'
@State resources: string = this.resmgr.getStringSync($r("app.string.test_string").id)
@State pixmap: PixelMap = this.resmgr.getDrawableDescriptor($r("app.media.icon").id).getPixelMap()
build() {
Column() {
Text($r('app.string.title'))
.width('100%')
.height(50)
.backgroundColor($r('app.color.text_color'))
.fontColor(Color.White)
.fontSize(20)
.padding({ left: 15 })
Text(`${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({
top: 40
})
Button() {
Text('disable')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 50
})
.backgroundColor('#0D9FFB')
.width('50%')
.height('5%')
.onClick(() = > {
// 非使能
overlay.setOverlayEnabled("libraryOverlay", false, (err, data) = > {
if (err && err.code != 0) {
console.log("error:" + JSON.stringify(err));
this.message = this.resmgr.getStringSync($r('app.string.unEnableFailed').id);
} else {
console.log("data:" + JSON.stringify(data));
this.message = this.resmgr.getStringSync($r('app.string.unEnableSuccess').id);
}
})
})
Button() {
Text('enable')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('50%')
.height('5%')
.onClick(() = > {
// 使能
overlay.setOverlayEnabled("libraryOverlay", true, (err, data) = > {
if (err && err.code != 0) {
console.log("error:" + JSON.stringify(err));
this.message = this.resmgr.getStringSync($r('app.string.enableFailed').id);
} else {
this.message = this.resmgr.getStringSync($r('app.string.enableSuccess').id);
}
})
})
Button() {
Text('addResource')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('50%')
.height('5%')
.onClick(() = > {
let path = getContext().bundleCodeDir + "/libraryRuntimeOverlay-default-signed.hsp";
try {
let ret = this.resmgr.addResource(path);
console.error("addResource: ret" + JSON.stringify(ret));
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
console.error(`addResource failed, error code: ${code}, message: ${message}.`);
}
this.pixmap = this.resmgr.getDrawableDescriptor($r("app.media.icon").id).getPixelMap();
this.resources = this.resmgr.getStringSync($r("app.string.test_string").id);
})
Button() {
Text('removeResource')
.fontSize(20)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('50%')
.height('5%')
.onClick(() = > {
let path = getContext().bundleCodeDir + "/libraryRuntimeOverlay-default-signed.hsp";
try {
this.resmgr.removeResource(path);
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
console.error(`removeResource failed, error code: ${code}, message: ${message}.`);
}
this.pixmap = this.resmgr.getDrawableDescriptor($r("app.media.icon").id).getPixelMap();
this.resources = this.resmgr.getStringSync($r("app.string.test_string").id);
})
Image(this.pixmap)
.width(100)
.height(100)
Text(this.resources)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
.height('100%')
}
}
審核編輯 黃宇
-
OpenHarmony
+關(guān)注
關(guān)注
25文章
3722瀏覽量
16321
發(fā)布評論請先 登錄
相關(guān)推薦
評論