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

評論