[OpenHarmony北向应用开发]将应用资源目录rawfile中的文件推送到应用沙箱
  noedAHRF1iby 2023年11月02日 23 0
  • 在应用开发调试时,可能需要向应用沙箱下推送一些文件用于应用访问或者调试,本文介绍了如何放置在应用资源目录rawfile中的文件推送到应用沙箱。并且在提供一个样例Demo用于读者老爷参考学习。

  • 样例demo下载链接:https://gitee.com/from-north-to-north/OpenHarmony_hap/tree/master/rawfile_to_sandbox

  • 笔者开发环境:(本文提供的样例demo 一定得是以下IDE和SDK版本或者更高版本才能编译运行)

    • 开发板:润和软件DAYU200开发板
    • OpenHarmony版本:OpenHarmony3.2 release
    • IDE:DevEco Studio 3.1.0.400
    • SDK:API9(3.2.11.9)

  • 通过本文您将了解: 1、应用资源resources目录和应用沙箱的概念 2、将应用资源目录rawfile中的文件推送到应用沙箱

(目录)


文章开始首先要熟悉两个概念,OpenHarmony应用开发中 应用资源目录中的rawfile目录应用沙箱是什么?

1. 应用资源目录中的rawfile目录 是什么

  • OpenHarmony中应用开发使用的各类资源文件会被放进应用资源目录中,它在应用源码中长下面这个样子。 76e43fd045be8fc455d914358194300f827245 1.png

  • 应用资源resources目录包括三大类目录,一类为base目录,一类为限定词目录,还有一类就是rawfile目录。

  • 应用资源目录中的rawfile目录特点

    • 组织形式:支持创建多层子目录,目录名称可以自定义,文件夹内可以自由放置各类资源文件。rawfile目录的文件不会根据设备状态去匹配不同的资源。
    • 编译方式:目录中的资源文件会被直接打包进应用,不经过编译,也不会被赋予资源文件ID。
    • 引用方式:通过指定文件路径和文件名来引用。
  • 参考链接: https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/resource-categories-and-access.md

2. 应用沙箱 是什么

  • 应用沙箱是一种以安全防护为目的的隔离机制,避免数据受到恶意路径穿越访问。在这种沙箱的保护机制下,应用可见的目录范围即为“应用沙箱目录”。

  • OpenHarmony提供应用沙箱机制,增加目录可见性数据访问防线,减少了应用数据和用户隐私信息泄露,建立了更加严格安全的应用沙盒隔离能力。

  • 详细可参考:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/file-management/app-sandbox-directory.md

    • image.png
  • 应用沙箱实现源码:

    • https://gitee.com/openharmony/startup_appspawn/blob/master/util/src/sandbox_utils.cpp
    • https://gitee.com/openharmony/startup_appspawn
      • 屏幕截图 20230511 111408.png

3.向应用沙箱推送文件

  • 参考资料:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/file-management/send-file-to-app-sandbox.md

  • 开发者在应用开发调试时,可能需要向应用沙箱下推送一些文件以期望在应用内访问或测试,此时有两种方式:

    • 第一种:可以通过DevEco Studio向应用安装路径中放入目标文件,详见应用安装资源访问。
    • 第二种:在具备设备环境时,可以使用另一种更为灵活的方式,通过hdc工具来向设备中应用沙箱路径推送文件。即本文介绍的内容。
  • 本文介绍的就是第一种方式——通过DevEco Studio向应用安装路径中放入目标文件,也就是在应用资源目录rawfile目录中放入文件,然后将其推送至沙箱路径。

3.1 样例demo实现步骤:

  • 新建应用,创建资源文件,在rawfile下面新建文件。笔者在样例中新建的的是input.txt

    • image.png
  • 获取context上下文,src/main/ets/entryability/EntryAbility.ts

  onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    
    globalThis.abilityContext = this.context
    //用全局对象获取context类的接口
    globalThis.context = this.context
    ...
}
  • 将应用资源目录rawfile中的文件推送到应用沙箱,实际上是通过沙箱与公共路径间文件的复制来完成的,使用到的API有getRawFd ,还使用到了一些文件管理相关的api
import fs from '@ohos.file.fs';

@Entry
@Component
struct Index {
  @State message: string = 'rawfile_copy_to_sandbox'

  //沙箱路径
  dir:string = globalThis.abilityContext.filesDir + "/";

  //从rawfile中读取input.txt文件,在log中显示
  private async readfile_from_rawfile() {
    try {
      let uint8Array = await globalThis.context.resourceManager.getRawFileContent('rawfile/input.txt');
      let str = String.fromCharCode.apply(null, new Uint8Array(uint8Array.buffer));
      console.info("[rawfile_copy_to_sandbox] ———————————————————————————————————————————————————————");
      console.info("[rawfile_copy_to_sandbox] rawfile中的input.txt内容为" + str);

    } catch (error) {
      console.info("[rawfile_copy_to_sandbox] ———————————————————————————————————————————————————————");
      console.info("[rawfile_copy_to_sandbox] rawfile中的input.txt内容读取失败" + error);
    }
  }

  //用来拷贝rawfile文件中的input.txt到应用沙箱目录下
  private async copy_rawfile__to_sandbox() {
    try {

      let file = this.dir+"input.txt";
      let sss = fs.createStreamSync(file, "w");//没有会创建一个空的input.txt
      sss.closeSync();

      //获取rawfile下input.txt
      globalThis.context.resourceManager.getRawFileDescriptor('rawfile/input.txt',(error, value) => {

        if (error != null) {  //getRawFileDescriptor运行失败
          console.info("[rawfile_copy_to_sandbox] ———————————————————————————————————————————————————————");
          console.log("[rawfile_copy_to_sandbox] getRawFileDescriptor api 运行失败: ${error.code}, message: ${error.message}.");
          console.log("[rawfile_copy_to_sandbox] 未能成功将rawfile下的input.txt文件拷贝到应用沙箱下 ");
        } else {             //getRawFileDescriptor运行成功
          let fd = value.fd;
          fs.copyFileSync(fd, file);
          console.info("[rawfile_copy_to_sandbox] ———————————————————————————————————————————————————————");
          console.log("[rawfile_copy_to_sandbox] getRawFileDescriptor api 运行成功");
          console.log("[rawfile_copy_to_sandbox] 成功将rawfile下的input.txt文件拷贝到应用沙箱下");
        }

      });

    } catch (error) {
      console.info("[rawfile_copy_to_sandbox] ———————————————————————————————————————————————————————");
      console.info("[rawfile_copy_to_sandbox] getRawFileDescriptor api 运行失败" + error);
      console.log("[rawfile_copy_to_sandbox] 未能成功将rawfile下的input.txt文件拷贝到应用沙箱下");
    }
  }

  build() {
    Row() {
      Column() {

        Button(this.message)
          .fontSize(25)
          .margin({top:0})
          .fontWeight(FontWeight.Normal)
          .backgroundColor(Color.Green) //设置按钮颜色
          .onClick(() => {

            console.info("[rawfile_copy_to_sandbox] 沙箱路径是"+ this.dir);

            //用来复制rawfile文件中的input.txt到沙箱目录下
            //调用的是私有的自定义的copy_rawfile__to_sandbox方法
            this.copy_rawfile__to_sandbox();
            this.readfile_from_rawfile();

          })

      }
      .width('100%')
    }
    .height('100%')
  }
}

3.2 样例实现效果

  • 日志显示:日志显示rawfile目录下的input.txt成功推送到/data/app/el2/100/base/com.sandbox.rawfile_to_sandbox/haps/entry/files/沙箱路径下 image.png
  • 进入设备shell终端 image.png

附件链接:https://ost.51cto.com/resource/2732

本文作者:离北况归

想了解更多关于开源的内容,请访问:​

​51CTO 开源基础软件社区​

​https://ost.51cto.com/#bkwz​

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

noedAHRF1iby