HarmonyOS开发实例:【使命延时调理】

火影  论坛元老 | 2024-7-12 17:33:49 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1757|帖子 1757|积分 5271

 

介绍

本示例利用[@ohos.WorkSchedulerExtensionAbility] 、[@ohos.net.http]、[@ohos.notification] 、[@ohos.bundle]、[@ohos.fileio] 等接口,实现了设置背景使命、下载更新包 、保存更新包、发送关照 、安装更新包实现升级的功能。
结果预览



利用说明

  • 安装本应用之前,先编译好未署名的应用包,然后在终端实验工程里的脚本,目录为:WorkScheduler/signTool/b_sign_hap_release.bat;
  • 未毗连wifi状态下进入应用;
  • 进入首页后毗连wifi;
  • 背景判定版本号后会下载新的升级包,并在页面中给出弹窗扣问是否安装,点击“确定”按钮;
  • 应用会安装已经下载的升级包,实现版本更新,安装后会回到设备桌面,此时点击应用图标,可以看到版本已经是新版本了。
  • 运行自动化测试用例时,必须利用下令行装包,不能利用ide自动装包,安装自动化测试包之前,先编译好未署名的测试包, 然后在终端实验工程里的脚本,目录为:WorkScheduler/signTool/a_sign_hap_release.bat;
  • 运行自动化测试应用时需要利用如下下令:
  1. hdc shell aa test -b ohos.samples.workschedulerextensionability -m entry_test -s unittest OpenHarmonyTestRunner -s class ActsAbilityTest -s timeout 150000
复制代码
代码解读

  1. entry/src/main/ets/
  2. |---Application
  3. |   |---MyAbilityStage.ets                  // 入口文件
  4. |---feature
  5. |   |---WorkSchedulerSystem.ets             // 封装各个功能接口
  6. |---MainAbility
  7. |   |---MainAbility.ets                     // 请求权限
  8. |---pages
  9. |   |---Index.ets                           // 首页
  10. |---util
  11. |   |---Logger.ets                          // 日志文件
  12. |---WorkSchedulerAbility
  13. |   |---WorkSchedulerAbility.ets            // 延时任务触发后的回调
复制代码


详细实现

鸿蒙next开发知识更新在:gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md


  • 设置延时使命、下载更新包、保存更新包、发送关照、安装更新包的功能接口都封装在WorkSchedulerSystem中, 源码参考:[WorkSchedulerSystem.ets]
  1. /*
  2. * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. *     http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import fs from '@ohos.file.fs';
  16. import notificationManager from '@ohos.notificationManager';
  17. import Notification from '@ohos.notification';
  18. import bundle from '@ohos.bundle.installer';
  19. import account from '@ohos.account.osAccount';
  20. import workScheduler from '@ohos.resourceschedule.workScheduler';
  21. import http from '@ohos.net.http';
  22. import { Logger } from '../utils/Logger';
  23. const FILE_NAME = '/UpdateWorkScheduler.hap';
  24. const BUNDLE_NAMES = ['ohos.samples.workschedulerextensionability'];
  25. const INSTALL_PARAMETER = 1;
  26. export namespace WorkSchedulerSystem {
  27.   /**
  28.    * Store the file to the specified directory.
  29.    *
  30.    * @param pathDir Path to save the file.
  31.    * @param content The contents of the file to be saved.
  32.    */
  33.   export function saveFile(pathDir: string, content: ArrayBuffer): void {
  34.     try {
  35.       let filePath = pathDir + FILE_NAME;
  36.       let fd = fs.openSync(filePath, 0o2 | 0o100).fd;
  37.       fs.writeSync(fd, content);
  38.       fs.closeSync(fd);
  39.     } catch (err) {
  40.       Logger.error(`saveFile failed, code is ${err.code}, message is ${err.message}`);
  41.     }
  42.   }
  43.   /**
  44.    * Sending a Notification.
  45.    *
  46.    * @param bundleName Check the name of the application that has permission.
  47.    * @permission ohos.permission.NOTIFICATION_CONTROLLER
  48.    */
  49.   export async function handleNotification(bundleName: string): Promise<void> {
  50.     await notificationManager.requestEnableNotification();
  51.     Notification.subscribe({
  52.       onConsume: (data) => {
  53.         if (data.request.content.normal.text === 'isReady') {
  54.           AppStorage.SetOrCreate('isShowDialog', true);
  55.         }
  56.       }
  57.     }, {
  58.       bundleNames: BUNDLE_NAMES
  59.     })
  60.   }
  61.   /**
  62.    * Publishes a notification of the specified content.
  63.    *
  64.    * @param title Title of Notice.
  65.    * @param text Content of Notification Text.
  66.    * @param additionalText Additional text.
  67.    * @permission ohos.permission.NOTIFICATION_CONTROLLER
  68.    */
  69.   export function publishNotification(title: string, text: string, additionalText: string): void {
  70.     notificationManager.publish({
  71.       content: {
  72.         contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
  73.         normal: {
  74.           title,
  75.           text,
  76.           additionalText
  77.         }
  78.       }
  79.     })
  80.   }
  81.   /**
  82.    * Install the application package in the specified path.
  83.    *
  84.    * @param filePath An array of paths to hold the installation package.
  85.    * @permission ohos.permission.INSTALL_BUNDLE
  86.    */
  87.   export async function installBundle(filePath: Array<string>): Promise<void> {
  88.     try {
  89.       let bundleInstall = await bundle.getBundleInstaller();
  90.       let userId = await account.getAccountManager().getOsAccountLocalIdFromProcess();
  91.       bundleInstall.install(filePath, {
  92.         userId: userId,
  93.         installFlag: INSTALL_PARAMETER,
  94.         isKeepData: false
  95.       }, (status, statusMessage) => {
  96.         Logger.info(`installBundle filepath is ${filePath}`);
  97.         Logger.info(`installBundle code is ${status.code}, message is ${JSON.stringify(statusMessage)}`);
  98.       })
  99.     } catch (err) {
  100.       Logger.error(`installBundle failed, code is ${err.code}, message is ${err.message}`);
  101.     }
  102.   }
  103.   /**
  104.    * Register the delayed task and pass the parameters.
  105.    *
  106.    * @param version Current application version.
  107.    * @param bundleName The name of the application package for which the task needs to be registered.
  108.    * @param filePath Storage address of the application package.
  109.    */
  110.   export async function startUpdateSample(version: string, bundleName: string, filePath: string): Promise<void> {
  111.     try {
  112.       let workInfo = {
  113.         workId: 1,
  114.         bundleName: bundleName,
  115.         abilityName: 'WorkSchedulerAbility',
  116.         networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
  117.         parameters: {
  118.           version: version,
  119.           filePath: filePath
  120.         }
  121.       };
  122.       workScheduler.startWork(workInfo);
  123.     }
  124.     catch (err) {
  125.       Logger.error(`startWork failed, code is ${err.code}, message is ${err.message}`);
  126.     }
  127.   }
  128.   /**
  129.    * Register the delayed task and pass the parameters.
  130.    *
  131.    * @param url Url of the application package.
  132.    * @permission ohos.permission.INTERNET
  133.    */
  134.   export async function getNewHap(url: string): Promise<http.HttpResponse> {
  135.     try {
  136.       return await http.createHttp().request(
  137.         url,
  138.         {
  139.           expectDataType: http.HttpDataType.ARRAY_BUFFER
  140.         });
  141.     } catch (err) {
  142.       Logger.error(`get result failed, code is ${err.code}, message is ${err.message}`);
  143.     }
  144.   }
  145. }
复制代码


  • 设置延时使命:在运行示例时会在[MainAbility.ets] 通过WorkSchedulerSystem.startUpdateSample()方法调用workScheduler.startWork()建立使命;
  • 下载更新包:当使命条件满意后,会在[WorkSchedulerAbility.ets]通过WorkSchedulerSystem.getNewHap()方法调用http.createHttp().request()接口下载需要的文件;
  • 保存更新包:通过WorkSchedulerSystem.saveFile()来实现,受限调用fileio.openSync()创建文件,然后调用fileio.writeSync()将下载的内容写入指定文件内;
  • 发送关照:在[WorkSchedulerAbility.ets] 中通过WorkSchedulerSystem.publishNotification()方法,调用Notification.publish()接口发送指定内容的信息;
  • 吸取关照:在[MainAbility.ets]中通过WorkSchedulerSystem.handleNotification()方法调用Notification.subscribe()接口获取信息,根据信息内容决定是否提示用户升级;
  • 安装更新包:在[WorkSchedulerAbility.ets] 通过WorkSchedulerSystem.installBundle()方法实现,起首调用bundle.getBundleInstaller()获取Installer对象,然后调用bundleInstall.install()接口实现装包,完成升级。
最后呢,许多开发朋侪不知道需要学习那些鸿蒙技术?鸿蒙开发岗位需要掌握那些核心技术点?为此鸿蒙的开发学习必须要系统性的进行。

而网上有关鸿蒙的开发资料非常的少,假如你想学好鸿蒙的应用开发与系统底层开发。你可以参考这份资料,少走许多弯路,节省没须要的贫苦。由两位前阿里高级研发工程师联合打造《鸿蒙NEXT星河版OpenHarmony开发文档》里面内容包罗了(ArkTS、ArkUI开发组件、Stage模型、多端摆设、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(Harmony NEXT)技术知识点
假如你是一名Android、Java、前端等等开发职员,想要转入鸿蒙方向发展。可以直接领取这份资料辅助你的学习。下面是鸿蒙开发的学习门路图。

高清完整版请点击→《鸿蒙NEXT星河版开发学习文档》
针对鸿蒙成长门路打造的鸿蒙学习文档。话不多说,我们直接看详细资料鸿蒙(OpenHarmony )学习手册(共计1236页)与鸿蒙(OpenHarmony )开发入门教学视频,资助大家在技术的道路上更进一步。
《鸿蒙 (OpenHarmony)开发学习视频》


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


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

获取这份鸿蒙星河版学习资料,请点击→《鸿蒙NEXT星河版开发学习文档》
OpenHarmony北向、南向开发环境搭建

《鸿蒙开发基础》

  • ArkTS语言
  • 安装DevEco Studio
  • 运用你的第一个ArkTS应用
  • ArkUI声明式UI开发
  • .……

《鸿蒙开发进阶》

  • Stage模型入门
  • 网络管理
  • 数据管理
  • 电话服务
  • 分布式应用开发
  • 关照与窗口管理
  • 多媒体技术
  • 安全技能
  • 使命管理
  • WebGL
  • 国际化开发
  • 应用测试
  • DFX面向未来设计
  • 鸿蒙系统移植和裁剪定制
  • ……

《鸿蒙开发实战》

  • ArkTS实践
  • UIAbility应用
  • 网络案例
  • ……

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

鸿蒙—作为国家主力推送的国产操作系统。部分的高校已经取消了安卓课程,从而开设鸿蒙课程;企业纷纷跟进启动了鸿蒙研发
而且鸿蒙是完全具备无与伦比的机遇和潜力的;预计到年底将有 5,000 款的应用完成原生鸿蒙开发,未来将会支持 50 万款的应用那么这么多的应用需要开发,也就意味着需要有更多的鸿蒙人才。鸿蒙开发工程师也将会迎来爆发式的增长,学习鸿蒙势在必行!



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

火影

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表