电子说
本工程使用[@ohos.app.ability.common] 接口中的AbilityContext类,获取资源管理器resourceManager,使用[@ohos.resourceManager.d.ts] 中的接口,展示了格式化字符串查询、基于指定屏幕分辨率查询媒体资源、获取系统资源管理对象等基础功能,以及展示了资源静态overlay以及运行时overlay的特性功能。
此界面为主页面,其中展示了资源管理API各类接口的调用以及特性Overlay场景功能。其作用有:
1、点击资源API调用示例按钮,可跳转到资源API示例页面
2、点击Overlay使用示例,可以跳转到Overlay的使用示例界面。
开发前请熟悉鸿蒙开发指导文档 :[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md
]
此页面展示了当前资源管理接口的调用以及接口对应的返回结果。
此页面展示静态overlay功能,功能使用如下:
1、静态overlay是默认使能的,当前显示的是静态overlay中的字符串和图标。
2、点击Disable可以触发去使能,重启应用可以恢复显示应用的字符串和图标。
3、点击enable可以触发使能,重启应用可以再次显示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%')
}
}
此页面展示运行时overlay功能,功能使用如下:
1、点击addResource可以触发运行时overlay,此时会使用运行时overlay中的资源覆盖之前的字符串和图标。
2、点击removeResource可以触发移除运行时overlay,此时会移除运行时overlay,恢复到覆盖前的字符串和图标。
entry/src/main/ets/
|---entryability
|---pages
| |---Index.ets // 场景首页
| |---BasicResources.ets // 基础资源场景
| |---Overlay.ets // overlay场景
|---libraryOverlay // 静态overlay
|---libraryRuntimeOverlay // 运行时overlay
1、使用getContext()接口获取context对象,使用context.resourceManager获取资源管理对象,然后调用resourceManager内部的相关接口获取对应资源,例如:
2、导包resourceManager,使用resourceManager.getSystemResourceManager()获取系统资源管理对象,然后获取系统资源。
/*
* 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 > {
// 获取仅系统资源管理对象
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%')
}
}
1、静态overlay主要是通过加载overly中的资源实现资源覆盖,需要在对应的module.json中添加"targetModuleName":"entry", 表示覆盖entry中的资源,默认使能,也可调用包管理接口进行使能和去使能。
使用步骤为:在安装完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资源加载,主要是在应用运行过程中实现资源的覆盖,需要应用主动调用资源的addResource接口实现资源的覆盖以及资源的移除,此功能不持久化。
使用步骤为: 在安装完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
HarmonyOS与OpenHarmony鸿蒙文档籽料:mau123789是v直接拿
/*
* 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%')
}
}
审核编辑 黄宇
全部0条评论
快来发表一下你的评论吧 !