0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

HarmonyOS开发实例:【任务延时调度】

jf_46214456 来源:jf_46214456 作者:jf_46214456 2024-04-15 09:26 次阅读

介绍

本示例使用[@ohos.WorkSchedulerExtensionAbility] 、[@ohos.net.http]、[@ohos.notification] 、[@ohos.bundle]、[@ohos.fileio] 等接口,实现了设置后台任务、下载更新包 、保存更新包、发送通知 、安装更新包实现升级的功能。

效果预览

image.png

使用说明

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

代码解读

entry/src/main/ets/
|---Application
|   |---MyAbilityStage.ets                  // 入口文件
|---feature
|   |---WorkSchedulerSystem.ets             // 封装各个功能接口
|---MainAbility
|   |---MainAbility.ets                     // 请求权限
|---pages
|   |---Index.ets                           // 首页
|---util
|   |---Logger.ets                          // 日志文件
|---WorkSchedulerAbility
|   |---WorkSchedulerAbility.ets            // 延时任务触发后的回调
鸿蒙HarmonyOS与OpenHarmony技术
+mau123789是v直接拿取

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

具体实现

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

  • 设置延时任务、下载更新包、保存更新包、发送通知、安装更新包的功能接口都封装在WorkSchedulerSystem中, 源码参考:[WorkSchedulerSystem.ets]
/*

 * Copyright (c) 2023-2024 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 fs from '@ohos.file.fs';

import notificationManager from '@ohos.notificationManager';

import Notification from '@ohos.notification';

import bundle from '@ohos.bundle.installer';

import account from '@ohos.account.osAccount';

import workScheduler from '@ohos.resourceschedule.workScheduler';

import http from '@ohos.net.http';

import { Logger } from '../utils/Logger';



const FILE_NAME = '/UpdateWorkScheduler.hap';

const BUNDLE_NAMES = ['ohos.samples.workschedulerextensionability'];

const INSTALL_PARAMETER = 1;



export namespace WorkSchedulerSystem {

  /**

   * Store the file to the specified directory.

   *

   * @param pathDir Path to save the file.

   * @param content The contents of the file to be saved.

   */

  export function saveFile(pathDir: string, content: ArrayBuffer): void {

    try {

      let filePath = pathDir + FILE_NAME;

      let fd = fs.openSync(filePath, 0o2 | 0o100).fd;

      fs.writeSync(fd, content);

      fs.closeSync(fd);

    } catch (err) {

      Logger.error(`saveFile failed, code is ${err.code}, message is ${err.message}`);

    }

  }



  /**

   * Sending a Notification.

   *

   * @param bundleName Check the name of the application that has permission.

   * @permission ohos.permission.NOTIFICATION_CONTROLLER

   */

  export async function handleNotification(bundleName: string): Promise< void > {

    await notificationManager.requestEnableNotification();

    Notification.subscribe({

      onConsume: (data) = > {

        if (data.request.content.normal.text === 'isReady') {

          AppStorage.SetOrCreate('isShowDialog', true);

        }

      }

    }, {

      bundleNames: BUNDLE_NAMES

    })

  }



  /**

   * Publishes a notification of the specified content.

   *

   * @param title Title of Notice.

   * @param text Content of Notification Text.

   * @param additionalText Additional text.

   * @permission ohos.permission.NOTIFICATION_CONTROLLER

   */

  export function publishNotification(title: string, text: string, additionalText: string): void {

    notificationManager.publish({

      content: {

        contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,

        normal: {

          title,

          text,

          additionalText

        }

      }

    })

  }



  /**

   * Install the application package in the specified path.

   *

   * @param filePath An array of paths to hold the installation package.

   * @permission ohos.permission.INSTALL_BUNDLE

   */

  export async function installBundle(filePath: Array< string >): Promise< void > {

    try {

      let bundleInstall = await bundle.getBundleInstaller();

      let userId = await account.getAccountManager().getOsAccountLocalIdFromProcess();

      bundleInstall.install(filePath, {

        userId: userId,

        installFlag: INSTALL_PARAMETER,

        isKeepData: false

      }, (status, statusMessage) = > {

        Logger.info(`installBundle filepath is ${filePath}`);

        Logger.info(`installBundle code is ${status.code}, message is ${JSON.stringify(statusMessage)}`);

      })

    } catch (err) {

      Logger.error(`installBundle failed, code is ${err.code}, message is ${err.message}`);

    }

  }



  /**

   * Register the delayed task and pass the parameters.

   *

   * @param version Current application version.

   * @param bundleName The name of the application package for which the task needs to be registered.

   * @param filePath Storage address of the application package.

   */

  export async function startUpdateSample(version: string, bundleName: string, filePath: string): Promise< void > {

    try {

      let workInfo = {

        workId: 1,

        bundleName: bundleName,

        abilityName: 'WorkSchedulerAbility',

        networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,

        parameters: {

          version: version,

          filePath: filePath

        }

      };

      workScheduler.startWork(workInfo);

    }

    catch (err) {

      Logger.error(`startWork failed, code is ${err.code}, message is ${err.message}`);

    }

  }



  /**

   * Register the delayed task and pass the parameters.

   *

   * @param url Url of the application package.

   * @permission ohos.permission.INTERNET

   */

  export async function getNewHap(url: string): Promise< http.HttpResponse > {

    try {

      return await http.createHttp().request(

        url,

        {

          expectDataType: http.HttpDataType.ARRAY_BUFFER

        });

    } catch (err) {

      Logger.error(`get result failed, code is ${err.code}, message is ${err.message}`);

    }

  }

}
  • 设置延时任务:在运行示例时会在[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()接口实现装包,完成升级。

审核编辑 黄宇

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • WIFI
    +关注

    关注

    81

    文章

    5162

    浏览量

    199461
  • 鸿蒙
    +关注

    关注

    55

    文章

    1641

    浏览量

    42123
  • HarmonyOS
    +关注

    关注

    79

    文章

    1861

    浏览量

    29267
  • OpenHarmony
    +关注

    关注

    23

    文章

    3322

    浏览量

    15161
收藏 人收藏

    评论

    相关推荐

    STM32F103 FreeRTOS任务调度异常的原因?

    ) { vTaskDelay(500); //延时函数(任务调度) printf(\"Task1rn\");//串口打印 } } void Task2_Task(void
    发表于 04-16 06:24

    请问在ucosii中有些和时序有关的延时会发生任务调度吗?

    自从把ucosii 移植到stm32中,有个疑问,像一些与时序有关的延时,会导致任务调度吗?不是调用ucosii中的延时函数!
    发表于 07-08 04:35

    如何利用UCOS引发任务调度

    我看资料中的任务调度往往发生在程序延时中,程序释放CPU引发任务调度,但是我希望程序能够更快的运行,不想使用
    发表于 10-24 04:36

    有些UCOSii任务里面为什么能使用GUI_Delay为任务调度延时

    为什么在有些UCOSii任务里面可以使用GUI_Delay为任务调度延时
    发表于 03-20 03:42

    UCOSiii任务延时时间达到问题

    之前一个帖子发错版块了当延时时间到了后,时钟节拍任务会把该等待延时任务放入任务就绪表中,在寻找最高优先级的函数中会找到优先级最高的就绪
    发表于 04-06 04:36

    UCOSIII延时函数任务怎么调度

    OSTimeDlyHMSM(0,0,0,10,OS_OPT_TIME_PERIODIC,&err);延时10ms。对于这样的延时函数,会触发任务调度。我的问题是
    发表于 04-10 04:36

    UCOSIII延时任务调度怎么实现?

    STM32用UCOSIII去写程序,现在需要延时,但不能进行调度延时的时间是几百毫秒,改怎么搞?
    发表于 04-17 03:07

    UCOSIII任务中使用延时函数进行调度怎么设置?

    请教各位大神关于UCOSIII任务中使用延时函数进行调度的问题:假如我有4个串口中断,都是每隔500ms使用任务内建消息队列的OSTaskQPost向处理
    发表于 05-11 03:07

    FreeRTOS如何使用delay作为系统延时任务调度

    请教一个问题,最近在学习使用FreeRTOS,想像原子一样在delay.c里添加RTOS的系统支持,即使用tick时钟作延时。现在有几个问题:1、在启动任务调度器前,如果调用了delay_ms
    发表于 06-10 04:37

    请问delay_xms()延时,会不会引起任务调度

    delay_xms()延时,不会引起任务调度的意思应该是:这个函数不会主动引起任务调度,但是在延时
    发表于 06-17 04:36

    HarmonyOS应用开发-分布式任务调度

    ,体验HarmonyOS的分布式任务调度。您将建立什么在这个CodeLab中,你将创建DemoProject,并将Demo编译成HAP,此示例应用程序展示了如何使用分布式任务
    发表于 09-18 09:21

    如何使用Tracealyzer理解多任务调度

    调试器视图的补充。我们今天来了解一下如何通过Tracealyzer记录的数据获取任务优先级及执行时间相关的信息。优先级决定何时调度大多数RTOS使用固定优先级调度策略,开发人员为每个
    发表于 12-17 16:01

    时调度思想在单片机应用中的一个实例

    利用分时操作系统中的分时调度思想可以使一个多终端的系统快速响应各终端的要求。本文首先介绍分时操作系统中的分时调度思想, 然后以程控交换机的控制系统为例, 在简介控
    发表于 07-17 16:03 26次下载

    基于CANoe总线系统实时调度的仿真

    基于CANoe总线系统实时调度的仿真
    发表于 01-24 17:21 22次下载

    任务阈值调度算法

    针对当前云任务调度算法在密码云环境中无法实现任务实时处理的问题,提出一种基于滚动优化窗口的实时阈值调度方法。首先,将密钥调用环节融入密码任务
    发表于 11-24 17:08 5次下载
    云<b class='flag-5'>任务</b>阈值<b class='flag-5'>调度</b>算法