OpenHarmony实例:【资源管理器】

 介绍

本工程使用[@ohos.app.ability.common] 接口中的AbilityContext类,获取资源管理器resourceManager,使用[@ohos.resourceManager.d.ts]中的接口,展示了格式化字符串查询、基于指定屏幕分辨率查询媒体资源、获取系统资源管理对象等基础功能,以及展示了资源静态overlay以及运行时overlay的特性功能。

效果预览

主页

main

使用说明

此界面为主页面,其中展示了资源管理API各类接口的调用以及特性Overlay场景功能。其作用有:

1、点击资源API调用示例按钮,可跳转到资源API示例页面

2、点击Overlay使用示例,可以跳转到Overlay的使用示例界面。

资源API调用示例
资源API测试

main

使用说明

此页面展示了当前资源管理接口的调用以及接口对应的返回结果。

静态overlay场景
overlay场景

main

使用说明

此页面展示静态overlay功能,功能使用如下:

1、静态overlay是默认使能的,当前显示的是静态overlay中的字符串和图标。

2、点击Disable可以触发去使能,重启应用可以恢复显示应用的字符串和图标。

3、点击enable可以触发使能,重启应用可以再次显示overlay中的字符串和图标。

源码参考:[Overlay示例]在最后

运行时overlay场景
运行时overlay场景

main

使用说明

此页面展示运行时overlay功能,功能使用如下:

1、点击addResource可以触发运行时overlay,此时会使用运行时overlay中的资源覆盖之前的字符串和图标。

2、点击removeResource可以触发移除运行时overlay,此时会移除运行时overlay,恢复到覆盖前的字符串和图标。

具体实现

资源API调用示例具体实现:

1、使用getContext()接口获取context对象,使用context.resourceManager获取资源管理对象,然后调用resourceManager内部的相关接口获取对应资源,例如:

  • 获取字符串资源:resourceManager.getStringValue()
  • 获取字符串数组资源:resourceManager.getStringArrayValue()
  • 获取图片资源:resourceManager.getMediaContent()
  • 获取格式化字符串资源:resourceManager.getStringSync()
  • 获取指定屏幕分辨率媒体资源:resourceManager.getMediaContentBase64()

2、导包resourceManager,使用resourceManager.getSystemResourceManager()获取系统资源管理对象,然后获取系统资源。

鸿蒙OS开发更多内容↓点击HarmonyOS与OpenHarmony技术
鸿蒙技术文档开发知识更新库qr23.cn/AKFP8k在这。

搜狗高速浏览器截图20240326151450.png

源码参考:[资源API调用示例]

/*

 * 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%')

  }

}
overlay场景的具体实现:

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

源码参考:[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%')

  }

}

最后呢,很多开发朋友不知道需要学习那些鸿蒙技术?鸿蒙开发岗位需要掌握那些核心技术点?为此鸿蒙的开发学习必须要系统性的进行。

而网上有关鸿蒙的开发资料非常的少,假如你想学好鸿蒙的应用开发与系统底层开发。你可以参考这份资料,少走很多弯路,节省没必要的麻烦。由两位前阿里高级研发工程师联合打造《鸿蒙NEXT星河版OpenHarmony开发文档》里面内容包含了(ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(Harmony NEXT)技术知识点

如果你是一名Android、Java、前端等等开发人员,想要转入鸿蒙方向发展。可以直接领取这份资料辅助你的学习。下面是鸿蒙开发的学习路线图。

高清完整版请点击→《鸿蒙NEXT星河版开发学习文档》

针对鸿蒙成长路线打造的鸿蒙学习文档。话不多说,我们直接看详细资料鸿蒙(OpenHarmony )学习手册(共计1236页)与鸿蒙(OpenHarmony )开发入门教学视频,帮助大家在技术的道路上更进一步。

《鸿蒙 (OpenHarmony)开发学习视频》

图片

《鸿蒙生态应用开发V2.0白皮书》

图片

《鸿蒙 (OpenHarmony)开发基础到实战手册》

获取这份鸿蒙星河版学习资料,请点击→《鸿蒙NEXT星河版开发学习文档》

OpenHarmony北向、南向开发环境搭建

图片

《鸿蒙开发基础》

  1. ArkTS语言

  2. 安装DevEco Studio

  3. 运用你的第一个ArkTS应用

  4. ArkUI声明式UI开发

  5. .……

图片

《鸿蒙开发进阶》

  1. Stage模型入门

  2. 网络管理

  3. 数据管理

  4. 电话服务

  5. 分布式应用开发

  6. 通知与窗口管理

  7. 多媒体技术

  8. 安全技能

  9. 任务管理

  10. WebGL

  11. 国际化开发

  12. 应用测试

  13. DFX面向未来设计

  14. 鸿蒙系统移植和裁剪定制

  15. ……

图片

《鸿蒙开发实战》

  1. ArkTS实践

  2. UIAbility应用

  3. 网络案例

  4. ……

图片

 获取这份鸿蒙星河版学习资料,请点击→《鸿蒙NEXT星河版开发学习文档》

总结

鸿蒙—作为国家主力推送的国产操作系统。部分的高校已经取消了安卓课程,从而开设鸿蒙课程;企业纷纷跟进启动了鸿蒙研发

并且鸿蒙是完全具备无与伦比的机遇和潜力的;预计到年底将有 5,000 款的应用完成原生鸿蒙开发,未来将会支持 50 万款的应用那么这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才。鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值