导航栏·通知
状态栏设置下载进度条通知
/**
* @Description: 下载进度条状态栏通知class
*/
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
const TAG: string = '[PublishOperation]';
const DOMAIN_NUMBER: number = 0xFF00;
export class DownloadNotification {
public isSuperNotification: boolean = false;
private static instance: DownloadNotification;
private currentId: number = 1000; // 从1000开始,避免与系统通知ID冲突
constructor() {
this.queryProgressBarTemplate()
}
static getInstance(): DownloadNotification {
if (!DownloadNotification.instance) {
DownloadNotification.instance = new DownloadNotification();
}
return DownloadNotification.instance;
}
/**
* 生成下一个不重复的通知ID
* @returns 唯一的Number类型ID
*/
nextId(): number {
this.currentId++;
// 防止溢出,如果超过最大值则重置
if (this.currentId > Number.MAX_SAFE_INTEGER - 1000) {
this.currentId = 1000;
}
return this.currentId;
}
// 查询系统是否支持进度条模板
queryProgressBarTemplate() {
notificationManager.isSupportTemplate('downloadTemplate').then((data: boolean) => {
// data的值为true表示支持downloadTemplate模板类通知,false表示不支持
hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in supporting download template notification. data is ${data}`);
this.isSuperNotification = data;
}).catch((err: BusinessError) => {
hilog.error(DOMAIN_NUMBER, TAG, `Failed to support download template notification. Code is ${err.code}, message is ${err.message}`);
});
}
// 创建通知
createNotification(id: number, progressValue: number, title: string, fileName: string) {
hilog.info(DOMAIN_NUMBER, TAG, 'Start to publish notification.id:' + id + ',progressValue:' + progressValue + ',title:' + title + ',fileName:' + fileName);
let notificationRequest: notificationManager.NotificationRequest = {
id,
content: {
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: 'test_title',
text: 'test_text',
additionalText: 'test_additionalText'
}
},
// 构造进度条模板,name字段当前需要固定配置为downloadTemplate
template: {
name: 'downloadTemplate',
data: { title, fileName, progressValue }
}
};
// 发布通知
notificationManager.publish(notificationRequest, (err: BusinessError) => {
if (err) {
hilog.error(DOMAIN_NUMBER, TAG,
`Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
return;
}
hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in publishing notification.');
});
}
// 取消通知
cancelNotification(id: number) {
// cancel回调
let cancelCallback = (err: BusinessError): void => {
if (err) {
console.error(`Failed to cancel notification. Code is ${err.code}, message is ${err.message}`);
} else {
console.info(`Succeeded in canceling notification.`);
}
}
notificationManager.cancel(id, "label", cancelCallback);
}
}
/**
* 便捷函数:获取下一个通知ID
*/
export function getNextNotificationId(): number {
return DownloadNotification.getInstance().nextId();
}
简单使用:
// 第一步:entryAbility申请权限。
windowStage.loadContent('pages/Index', (err) => {
if (err.code) {
hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
return;
}
let requestEnableNotificationCallback = (err: BusinessError): void => {
if (err) {
hilog.error(0x0000, 'testTag', `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
} else {
hilog.info(0x0000, 'testTag', `[ANS] requestEnableNotification success`);
}
};
notificationManager.requestEnableNotification(this.context, requestEnableNotificationCallback);
});
}
//第二步:实例对象
notification: DownloadNotification = DownloadNotification.getInstance();
// 第三步:获取id
notificationId: number = getNextNotificationId();
// 第四步:开启监听并更新进度条
onDownloadProgress: (totalSize: number, transferredSize: number) => {
this.downLoadingProgress = this.downloadedSize + transferredSize;
// LogUtils.info(TAG,"Download progress:" + transferredSize + "of" + totalSize);
if (this.notification.isSuperNotification && this.type === MediaType.VIDEO) {
const currentProgress = Number(((this.downLoadingProgress / this.totalSize) * 100).toFixed(2));
// 满足任一条件就更新:进度变化超过1% 或者 进度为100%
if (Math.abs(currentProgress - this.lastProgressValue) >= 1 || currentProgress === 100) {
this.lastProgressValue = currentProgress;
this.notification.createNotification(this.notificationId, currentProgress, 'SJCAM X', this.fileName!!);
}
}
},
// 第五步:完成后取消对应的通知
onDataEnd: () => {
LogUtils.info("Data transfer complete");
this.notification.cancelNotification(this.notificationId);
}
浙公网安备 33010602011771号