ArtTS系统能力-通知的学习(3.1)

上篇回顾: ArtTS语言基础类库-容器类库内容的学习(2.10.2)

本篇内容: ArtTS系统能力-通知的学习(3.1)

一、 知识储备

1. 基础类型通知

按内容分成四类:

类型描述
NOTIFICATION_CONTENT_BASIC_TEXT普通文本类型
NOTIFICATION_CONTENT_LONG_TEXT长文本类型
NOTIFICATION_CONTENT_MULTILINE多行文本类型
NOTIFICATION_CONTENT_PICTURE图片类型

2. 带进度类型通知

在这里插入图片描述

3. 带事件响应类型通知

二、 效果一览

在这里插入图片描述

三、 源码剖析

import notificationManager from '@ohos.notificationManager'
import http from '@ohos.net.http'
import ResponseCode from '@ohos.net.http'
import image from '@ohos.multimedia.image'
import wantAgent from '@ohos.app.ability.wantAgent'

function basicText() {

  let notificationRequest = {
    id: 1,
    content: {
      contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
      normal: {
        title: '通知类型',
        text: '普通文本类型',
        additionalText: '我是补充标题'
      }
    }
  }

  notificationManager.publish(notificationRequest, err => {
    if (err) {
      console.error(`普通文本类型通知发布失败: ${err}`)
      return;
    }
    console.info('普通文本类型通知发布成功')
  })
}

function longText() {
  let notificationRequest = {
    id: 2,
    content: {
      contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT,
      longText: {
        title: '通知类型', //无效
        text: '长文本类型', //无效
        additionalText: '我是补充标题 ',

        longText: '我是长文本我是长文本我是长文本',
        briefText: '我是简明信息', //无效
        expandedTitle: '我是扩展文本'
      }
    }
  }

  notificationManager.publish(notificationRequest, err => {
    if (err) {
      console.error('长文本类型通知发布失败:' + err)
      return;
    }
    console.info('长文本类型通知发布成功')
  })
}

function multiline() {
  let notificationRequest = {
    id: 3,
    content: {
      contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE,
      multiLine: {
        title: '通知类型', //无效
        additionalText: '我是补充标题',
        text: '多行文本类型', //无效
        briefText: '我是简明信息', //无效
        longTitle: '我是长文本标题',
        lines: ['第一行', '第二行', '第三行', '第四行', '第五行']
      }
    }
  }

  notificationManager.publish(notificationRequest, err => {
    if (err) {
      console.error(`多行文本通知发布失败: ${err}`)
      return;
    }
    console.info('多行文本通知发布成功')
  })
}

function picture() {
  let imgUrl: string = 'https://img1.baidu.com/it/u=3241660985,1063915045&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1194';
  http.createHttp().request(imgUrl, (err, data) => {
    if (err) {
      console.error(`err is ${JSON.stringify(err)}`)
    } else {
      let code = data.responseCode;
      if (ResponseCode.ResponseCode.OK == code) {
        let res: any = data.result;
        let imageSource = image.createImageSource(res)
        let options = {
          alphaTye: 0, //透明度
          editable: false, //是否可编辑
          pixelFormat: 3, //像素格式
          scaleMode: 1, //缩略值
          size: { height: 100, wight: 100 } //创建图片大小
        }
        imageSource.createPixelMap(options).then(pixelMap => {
          let imagePixelMap: PixelMap = undefined;

          imagePixelMap = pixelMap;

          let notificationRequest = {
            id: 4,
            content: {
              contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
              picture: {
                title: '通知类型',
                text: '图片通知',
                additionalText: '我是补充标题',
                briefText: '我是简明信息',
                expandedTitle: '扩展消息',
                picture: imagePixelMap
              }
            }
          }

          notificationManager.publish(notificationRequest, err => { //	官方解释 :2024.06.30 图片类型通知。(预留能力,暂未支持)。
            if (err) {
              console.error(`图片类型通知发布失败: ${err}`)
              return;
            }
            console.info('图片类型通知发布成功')
          })
        })
      }
    }
  })
}

function progress() {
  let progress = 1;
  // for (let i = 0; i < 100; i++) {
  //   setTimeout(() => {
  //     progress += 1;
  //
  //   }, 100);
  // }

  //需要先查询系统是否支持进度条模板
  notificationManager.isSupportTemplate('downloadTemplate').then((data) => {
    let isSupport: boolean = data;
    if (isSupport) {
      let notificationRequest = {
        id: 5,
        content: {
          contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
          normal: {
            title: '下载通知',
            text: '我正在下载',
            additionalText: '下载通知标题'
          }
        },
        template: { // 构造进度条模板,name字段当前需要固定配置为 downloadTemplate
          name: 'downloadTemplate',
          data: {
            title: '文档下载',
            fileName: '阿吉',
            progressValue: 22
          }
        }
      }

      notificationManager.publish(notificationRequest, err => {
        if (err) {
          console.error(`下载进度提醒失败 ${err}`)
          return;
        }
        console.info('下载进度提醒正常')
      })
    }
  }).catch(err => {
    console.error(`暂不支持:${err.message}`)
  })
}

function action() {
  let wantAgentObj = null; //用于保存创建成功的wantAgent对象,后续使用其完成触发的动作
  let wantAgentInfo = { //通过 wantAgentInfo的operationType设置动作类型
    wants: [
      {
        deviceId: '',
        bundleName: 'com.aji.first',
        abilityName: 'com.aji.first.SecondAbility',
        action: '',
        entities: [],
        uri: '',
        parameters: {}
      }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
  }

  wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
    if (err) {
      console.error('失败: ' + JSON.stringify(err))
    } else {
      wantAgentObj = data;
    }
  })

  let notificationRequest = {6
    id: 6,
    content: {
      contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
      normal: {
        title: '标题',
        text: '进入应用',
        additionalText: '欢迎再次使用'
      },
      label: '阿吉',
      wantAgent: wantAgentObj
    }
  }

  notificationManager.publish(notificationRequest, err => {
    if (err) {
      console.error('发布失败' + err)
      return;
    }
    console.info('发布成功')
  })
}


@Entry
@Component
struct Index {
  build() {
    Column() {
      Button('普通文本类型').onClick(() => {
        basicText();
      })
        .margin(20)

      Button('长文本类型').onClick(() => {
        longText();
      })
        .margin(20)

      Button('多行文本类型').onClick(() => {
        multiline();
      })
        .margin(20)

      Button('图片类型').onClick(() => {
        picture();
      })
        .margin(20)

      Button('进度条类型').onClick(() => {
        progress();
      })
        .margin(20)

      Button('带意图类型').onClick(() => {
        action();
      })
        .margin(20)

    }
    .width('100%')
    .height('100%')
  }
}
<think>好的,我现在需要帮助用户找到ArtTS中清除缓存的方法。首先,我需要回忆一下ArtTS相关的文档内容。用户提供的引用中,提到了关于系统能力中的通知模块和@State的使用,但没有直接提到缓存管理。这可能意味着我需要从ArtTS的基础类库或系统能力中寻找相关功能。 ArtTS作为鸿蒙的应用开发框架,通常缓存管理可能属于存储或文件系统能力。我需要检查是否有类似Storage或Cache管理的模块。例如,鸿蒙的API中可能有提供清除应用缓存的接口,比如通过StorageHelper或类似工具类。 另外,用户提供的引用[2]提到了@State的使用,这可能与组件状态管理相关,但清除缓存更可能涉及系统级的API,而不是组件状态。可能需要查阅ArtTS的文档,查找是否有清除应用缓存的系统接口,例如使用Context对象的方法,或者调用系统服务来清理缓存目录下的文件。 假设ArtTS遵循类似其他移动开发框架的结构,清除缓存可能需要访问应用的文件存储路径,并删除缓存目录中的内容。例如,使用Context.getCacheDir()获取缓存目录,然后递归删除其中的文件。此外,可能还需要调用系统API来通知系统缓存已被清理,确保存储统计信息更新。 需要验证这些步骤是否符合ArtTS的具体实现。如果官方文档中没有明确说明,可能需要参考鸿蒙的开发文档,查找与ArtTS兼容的缓存管理方法。此外,还要注意权限问题,确保应用具有删除缓存文件的权限,这通常属于应用沙箱内的操作,不需要额外权限。 总结可能的步骤:获取应用的Context对象,通过Context的方法访问缓存目录,删除目录中的文件。或者使用封装好的Storage模块中的方法直接清除缓存。需要具体示例代码来演示这一过程,并确保符合ArtTS的语法规范。</think>在ArtTS中清除缓存通常涉及文件系统或存储模块的操作。根据现有参考资料,以下是实现方法: ### 清除缓存方法步骤 1. **获取应用上下文**: ```typescript let context = getContext(this) as common.UIAbilityContext ``` 2. **访问缓存目录**: ```typescript let cacheDir = context.cacheDir ``` 3. **删除缓存文件**: 使用文件管理模块递归删除目录: ```typescript import fileio from &#39;@ohos.fileio&#39; function clearCache(dirPath: string) { try { let dir = fileio.opendirSync(dirPath) let entry = dir.readSync() while (entry) { let fullPath = dirPath + &#39;/&#39; + entry.name if (entry.isFile()) { fileio.unlinkSync(fullPath) } else { clearCache(fullPath) // 递归删除子目录 } entry = dir.readSync() } fileio.rmdirSync(dirPath) // 删除空目录 } catch (err) { console.error(&#39;清除缓存失败:&#39;, err) } } ``` 4. **调用方法**: ```typescript clearCache(cacheDir) ``` ### 注意事项 - 需要导入`@ohos.fileio`模块 - 建议在异步任务中执行文件操作 - 删除前应检查文件访问权限 - 可配合进度通知功能实现可视化反馈[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值