HarmonyOS开发实例:【任务延时调度】
1.OpenHarmony南向开发案例:【智能风扇】2.鸿蒙HarmonyOS开发实例:【简单时钟】3.HarmonyOS开发实例:【状态管理】4.鸿蒙OS开发学习:【尺寸适配实现】5.OpenHarmony鸿蒙开发学习:【Ability的启动模式】6.鸿蒙HarmonyOS开发实战:【分布式音乐播放】7.HarmonyOS开发实例:【分布式数据管理】8.鸿蒙HarmonyOS开发实例:【分布式关系型数据库】9.OpenHarmony开发技术:【国际化】实例10.OpenHarmony开发案例:【分布式计算器】11.HarmonyOS开发实例:【数字管家app】12.HarmonyOS开发:【NFC配置流程】13.HarmonyOS开发:【数字管家app设备接入FA】14.鸿蒙OS开发实例:【HarmonyHttpClient】网络框架15.鸿蒙OS开发实例:【Native C++】16.HarmonyOS开发实例:【菜单app】17.OpenHarmony开发学习:【源码下载和编译】18.HarmonyOS开发实例:【自定义Emitter】19.鸿蒙OS开发学习:【第三方库调用】20.HarmonyOS开发学习:【DevEco Device Tool 安装配置(问题全解)】21.OpenHarmony开发实例:【鸿蒙.bin文件烧录】22.HarmonyOS开发实例:【app帐号管理】23.OpenHarmony实例应用:【常用组件和容器低代码】24.OpenHarmony南向嵌入式:【XR806开发板指导文档】25.OpenHarmony南向开发案例:【智能门锁】
26.HarmonyOS开发实例:【任务延时调度】
27.OpenHarmony开发案例:【自定义通知】28.OpenHarmony开发实例:【仿桌面应用】29.HarmonyOS开发实例:【事件的订阅和发布】30.OpenHarmony开发案例:【电影卡片】31.OpenHarmony南向开发案例:【智能体重秤】32.鸿蒙OS开发指导:【应用包签名工具】33.OpenHarmony开发实例:【分布式游戏鉴权应用】34.OpenHarmony开发实例:【新闻客户端】35.鸿蒙OpenHarmony Native API【Native_Bundle】36.HarmonyOS开发实战:【亲子拼图游戏】介绍
本示例使用[@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;
- 运行自动化测试应用时需要使用如下命令:
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直接拿取
具体实现
鸿蒙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()接口实现装包,完成升级。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了