介紹
本示例使用[@ohos.WorkSchedulerExtensionAbility] 、[@ohos.net.http]、[@ohos.notification] 、[@ohos.bundle]、[@ohos.fileio] 等接口,實(shí)現(xiàn)了設(shè)置后臺(tái)任務(wù)、下載更新包 、保存更新包、發(fā)送通知 、安裝更新包實(shí)現(xiàn)升級(jí)的功能。
效果預(yù)覽
使用說明
- 安裝本應(yīng)用之前,先編譯好未簽名的應(yīng)用包,然后在終端執(zhí)行工程里的腳本,目錄為:WorkScheduler/signTool/b_sign_hap_release.bat;
- 未連接wifi狀態(tài)下進(jìn)入應(yīng)用;
- 進(jìn)入首頁后連接wifi;
- 后臺(tái)判斷版本號(hào)后會(huì)下載新的升級(jí)包,并在頁面中給出彈窗詢問是否安裝,點(diǎn)擊“確定”按鈕;
- 應(yīng)用會(huì)安裝已經(jīng)下載的升級(jí)包,實(shí)現(xiàn)版本更新,安裝后會(huì)回到設(shè)備桌面,此時(shí)點(diǎn)擊應(yīng)用圖標(biāo),可以看到版本已經(jīng)是新版本了。
- 運(yùn)行自動(dòng)化測(cè)試用例時(shí),必須使用命令行裝包,不能使用ide自動(dòng)裝包,安裝自動(dòng)化測(cè)試包之前,先編譯好未簽名的測(cè)試包, 然后在終端執(zhí)行工程里的腳本,目錄為:WorkScheduler/signTool/a_sign_hap_release.bat;
- 運(yùn)行自動(dòng)化測(cè)試應(yīng)用時(shí)需要使用如下命令:
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 // 封裝各個(gè)功能接口
|---MainAbility
| |---MainAbility.ets // 請(qǐng)求權(quán)限
|---pages
| |---Index.ets // 首頁
|---util
| |---Logger.ets // 日志文件
|---WorkSchedulerAbility
| |---WorkSchedulerAbility.ets // 延時(shí)任務(wù)觸發(fā)后的回調(diào)
鴻蒙HarmonyOS與OpenHarmony技術(shù)
+mau123789是v直接拿取
具體實(shí)現(xiàn)
鴻蒙next開發(fā)知識(shí)更新在:[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md
]
- 設(shè)置延時(shí)任務(wù)、下載更新包、保存更新包、發(fā)送通知、安裝更新包的功能接口都封裝在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}`);
}
}
}
- 設(shè)置延時(shí)任務(wù):在運(yùn)行示例時(shí)會(huì)在[MainAbility.ets] 通過WorkSchedulerSystem.startUpdateSample()方法調(diào)用workScheduler.startWork()建立任務(wù);
- 下載更新包:當(dāng)任務(wù)條件滿足后,會(huì)在[WorkSchedulerAbility.ets]通過WorkSchedulerSystem.getNewHap()方法調(diào)用http.createHttp().request()接口下載需要的文件;
- 保存更新包:通過WorkSchedulerSystem.saveFile()來實(shí)現(xiàn),受限調(diào)用fileio.openSync()創(chuàng)建文件,然后調(diào)用fileio.writeSync()將下載的內(nèi)容寫入指定文件內(nèi);
- 發(fā)送通知:在[WorkSchedulerAbility.ets] 中通過WorkSchedulerSystem.publishNotification()方法,調(diào)用Notification.publish()接口發(fā)送指定內(nèi)容的信息;
- 接收通知:在[MainAbility.ets]中通過WorkSchedulerSystem.handleNotification()方法調(diào)用Notification.subscribe()接口獲取信息,根據(jù)信息內(nèi)容決定是否提示用戶升級(jí);
- 安裝更新包:在[WorkSchedulerAbility.ets] 通過WorkSchedulerSystem.installBundle()方法實(shí)現(xiàn),首先調(diào)用bundle.getBundleInstaller()獲取Installer對(duì)象,然后調(diào)用bundleInstall.install()接口實(shí)現(xiàn)裝包,完成升級(jí)。
審核編輯 黃宇
-
WIFI
+關(guān)注
關(guān)注
81文章
5372瀏覽量
207425 -
鴻蒙
+關(guān)注
關(guān)注
59文章
2507瀏覽量
43766 -
HarmonyOS
+關(guān)注
關(guān)注
79文章
2052瀏覽量
32120 -
OpenHarmony
+關(guān)注
關(guān)注
26文章
3823瀏覽量
18128
發(fā)布評(píng)論請(qǐng)先 登錄
如何利用UCOS引發(fā)任務(wù)調(diào)度?
有些UCOSii任務(wù)里面為什么能使用GUI_Delay為任務(wù)調(diào)度延時(shí)?
UCOSiii任務(wù)延時(shí)時(shí)間達(dá)到問題
UCOSIII延時(shí)函數(shù)任務(wù)怎么調(diào)度?
UCOSIII延時(shí)的任務(wù)調(diào)度怎么實(shí)現(xiàn)?
UCOSIII任務(wù)中使用延時(shí)函數(shù)進(jìn)行調(diào)度怎么設(shè)置?
FreeRTOS如何使用delay作為系統(tǒng)延時(shí)、任務(wù)調(diào)度
請(qǐng)問delay_xms()延時(shí),會(huì)不會(huì)引起任務(wù)調(diào)度?
HarmonyOS應(yīng)用開發(fā)-分布式任務(wù)調(diào)度
最遲預(yù)分配容錯(cuò)實(shí)時(shí)調(diào)度算法設(shè)計(jì)與分析
分時(shí)調(diào)度思想在單片機(jī)應(yīng)用中的一個(gè)實(shí)例
基于CANoe總線系統(tǒng)實(shí)時(shí)調(diào)度的仿真
云任務(wù)閾值調(diào)度算法

評(píng)論