用户通知服务-工具类封装小案例
基本介绍
通过案例我们能学习到:用户通知服务还有部分文件服务基础能力工具类的封装,教大家如何进行工具类封装。
主体功能:用户点击下载文件按钮,触发通知,也可以取消通知
操作环境
记得在module.json文件中配置网络权限
"requestPermissions":[
{
"name" : "ohos.permission.INTERNET",
"reason": "$string:internet",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"inuse"
}
}
],
代码实现
界面如下:
1、文本通知工具类
NotificationUtil.ets
import { notificationManager } from '@kit.NotificationKit';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
export class NotificationUtil {
/**
* 查询通知是否授权
*/
static async isNotificationEnabled(): Promise<boolean> {
return await notificationManager.isNotificationEnabled(); //查询通知是否授权。
}
/**
* 请求通知授权,第一次调用会弹窗让用户选择。
* @returns
*/
static async authorizeNotification(): Promise<boolean> {
let isEnabled = await NotificationUtil.isNotificationEnabled(); //查询通知是否授权
if (!isEnabled) { //未授权,拉起授权
try {
let context = getContext() as common.UIAbilityContext;
await notificationManager.requestEnableNotification(context);
return true;
} catch (e) {
return false;
}
} else {
return true;
}
}
/**
* 发起普通文本通知
*/
static publishText(notificationOptions: NotificationOptions): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
let notificationRequest: notificationManager.NotificationRequest = {
// 通知的唯一id
id: notificationOptions.id,
content: {
notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
normal: {
// 通知的标题
title: notificationOptions.title,
// 通知的内容
text: notificationOptions.text,
// 附加消息
additionalText: notificationOptions.additionalText,
}
}
};
notificationManager.publish(notificationRequest, (err: BusinessError) => {
if (err) {
console.log(`Failed to publish notification. Code is ${err.code}, message is ${err.message}`)
reject(err)
}
console.log('Succeeded in publishing notification.')
resolve(true)
});
})
}
/**
* 取消通知
*/
static cancel(id: number): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
notificationManager.cancel(id, (err: BusinessError) => {
if (err) {
console.log(`Failed to cancel notification. Code is ${err.code}, message is ${err.message}`)
reject(err)
}
console.log('Succeeded in cancel notification.')
resolve(true)
});
})
}
/**
* 取消所有通知
*/
static cancelAll(): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
notificationManager.cancelAll((err: BusinessError) => {
if (err) {
console.log(`Failed to cancel notification. Code is ${err.code}, message is ${err.message}`)
reject(err)
}
console.log('Succeeded in cancel notification.')
resolve(true)
});
})
}
}
interface NotificationOptions {
id: number
title: string
text: string
additionalText: string
}
2、文件通知工具类
FileUtil.ets
import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import request from '@ohos.request';
import { BusinessError } from '@ohos.base';
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir
export class FileUtil {
/**
* 判断文件是否存在
*/
static isExist(fileName: string, fileSuffix: string) {
// 判断文件是否存在,存在就删除
let path = filesDir + '/' + fileName + '.' + fileSuffix;
if (fs.accessSync(path)) {
fs.unlinkSync(path);
}
}
/**
* 下载文件
*/
static downloadFile(fileName: string, fileSuffix: string, fileUrl: string): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
// 判断文件是否已存在
FileUtil.isExist(fileName, fileSuffix)
request.downloadFile(context, {
url: fileUrl,
filePath: filesDir + '/' + fileName + '.' + fileSuffix
}).then((downloadTask: request.DownloadTask) => {
downloadTask.on('complete', () => {
resolve(true)
})
}).catch((err: BusinessError) => {
console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
reject(err)
});
})
}
}
3、页面的编写
Index.ets
import { NotificationUtil } from '../utils/NotificationUtil'
import { promptAction } from '@kit.ArkUI'
import { BusinessError } from '@kit.BasicServicesKit'
import { FileUtil } from '../utils/FileUtil'
@Entry
@Component
struct Index {
build() {
Column({ space: 20 }) {
Button('发起通知')
.onClick(async () => {
// 发起通知授权
let isSuccess = await NotificationUtil.authorizeNotification()
if (isSuccess) {
// 发起通知
NotificationUtil.publishText({
id: 1,
title: '百得知识库',
text: '百得知识库提醒你该学习了',
additionalText: '百得'
})
.then(() => {
promptAction.showToast({ message: '发起通知成功' })
}).catch((error: BusinessError) => {
promptAction.showToast({ message: '发起通知失败' + error.message })
})
} else {
promptAction.showToast({ message: '通知授权失败' })
}
}).margin(100)
Button('取消通知')
.onClick(async () => {
let flag = await NotificationUtil.cancel(1)
if (flag) {
promptAction.showToast({ message: '取消通知成功' })
return
}
promptAction.showToast({ message: '取消通知失败' })
})
Button('取消所有通知')
.onClick(async () => {
let flag = await NotificationUtil.cancelAll()
if (flag) {
promptAction.showToast({ message: '取消所有通知成功' })
return
}
promptAction.showToast({ message: '取消所有通知失败' })
}).margin(100)
Button('下载文件完成通知')
.onClick(() => {
FileUtil.downloadFile('hello', 'txt', 'http://121.41.123.231:8888/f/e01ace4294264594b632/?dl=1')
.then(async (data) => {
promptAction.showToast({ message: '文件下载成功' })
// 发起通知授权
let isSuccess = await NotificationUtil.authorizeNotification()
if (isSuccess) {
// 发起通知
NotificationUtil.publishText({
id: 2,
title: '百得知识库',
text: '文件下载成功',
additionalText: '百得'
})
.then((data) => {
if (data) {
promptAction.showToast({ message: '发起通知成功' })
return
}
promptAction.showToast({ message: '发起通知失败' })
}).catch((error: BusinessError) => {
promptAction.showToast({ message: '发起通知失败' + error.message })
})
} else {
promptAction.showToast({ message: '通知授权失败' })
}
})
.catch((error: BusinessError) => {
promptAction.showToast({ message: '文件下载失败' + error.message })
})
})
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
}
}