核心api:

NotificationManager.publish
request.downloadFile

0、效果:

HarmonyOS下载图片和消息通知

1、下载文件

官网api:

文档中心

private publishDownUI = (fileUrl: string, type: string) => {
    let context = getContext(this) as common.UIAbilityContext;
    // const fileUrl: string = 'https://xxx.com/1698228608592657408.mp4'
    const fileSuffixName = fileUrl.split('.')[fileUrl.split('.').length - 1]
    const fileFullName = fileUrl.split('/')[fileUrl.split('/').length - 1]
    console.log('context.filesDir', context.filesDir)
    const filePath = `${context.filesDir}${new Date().getTime() + '.' + fileSuffixName}`;
    this.setFileAddress = filePath
    try {
      request.downloadFile(context, { url: fileUrl,filePath: filePath }, (err, data) => {
        if (err) {
          console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
          return;
        }
        // 监听文件下载的实时情况 receivedSize已下载 totalSize总大小
        data.on('progress', (receivedSize, totalSize) => {
          this.downState = DownloadState.DOWNLOADING
          console.info("upload totalSize:" + totalSize + "  receivedSize:" + receivedSize);
          this.downFileProcess = {
            totalSize: totalSize,
            receivedSize: receivedSize
          }
        })
        // 监听文件下载完成
        data.on('complete', () => {
          this.downState = DownloadState.FINISHED
          console.info('Download task completed.');
        })
      });
    } catch (err) {
      console.error('err.code : ' + err.code + ', err.message : ' + err.message);
    }
  }

2、发送通知

官网

文档中心

以其中一个为例:

private publishNotification = (notificationRequest: NotificationManager.NotificationRequest) => {
    NotificationManager.publish(notificationRequest, (err) => {
      if (err) {
        console.error(`[ANS] failed to publish, error[${err}]`);
        return;
      }
      console.info(`[ANS] publish success`);
    });
  }
  private publishOrdinaryNotice = () => {
    let notificationRequest = {
      id: 1,
      content: {
        contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
        normal: {
          title: 'test_title',
          text: 'test_text',
          additionalText: 'test_additionalText',
        }
      }
    }
    this.publishNotification(notificationRequest)
  }

3、注意事项:

1、如果同时下载多个文件。会导致.on里面的的代码是后面下载的文件信息。

相关的讨论:华为开发者论坛

2、在使用ide的手机模拟器进行下载的时候 保存的路径是/data/storage/el2/base/haps/entry/files  但是我并没有在手机模拟器的文件中找到这个在哪里。不知道是有问题还是本来就找不到还是说我没找到

4、完整代码

import NotificationManager from '@ohos.notificationManager';
import image from '@ohos.multimedia.image';
import request from '@ohos.request';
import common from '@ohos.app.ability.common';
import promptAction from '@ohos.promptAction'
enum DownloadState {
  NOT_BEGIN = '未开始',
  DOWNLOADING = '下载中',
  PAUSE = '暂停',
  FINISHED = '已完成',
  CANCEL = '已取消'
}
@Entry
@Component
struct AccountUserSettingIndex {
  async aboutToAppear() {
    console.log('AccountUserSettingIndex')
    this.isSupportTemplate = await NotificationManager.isSupportTemplate('downloadTemplate')
  }
  @State isSupportTemplate: boolean = false
  @State downState: DownloadState = DownloadState.NOT_BEGIN
  @State downFileProcess: {totalSize: number, receivedSize: number} = {
    totalSize: 0,
    receivedSize: 0
  }
  @State setFileAddress: string = ''
  taskId = null
  private publishNotification = (notificationRequest: NotificationManager.NotificationRequest) => {
    NotificationManager.publish(notificationRequest, (err) => {
      if (err) {
        console.error(`[ANS] failed to publish, error[${err}]`);
        return;
      }
      console.info(`[ANS] publish success`);
    });
  }
  private publishOrdinaryNotice = () => {
    let notificationRequest = {
      id: 1,
      content: {
        contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知
        normal: {
          title: 'test_title',
          text: 'test_text',
          additionalText: 'test_additionalText',
        }
      }
    }
    this.publishNotification(notificationRequest)
  }
  private publishLongOrdinaryNotice = () => {
    let notificationRequest = {
      id: 1,
      content: {
        contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // 长文本类型通知
        longText: {
          title: 'test_title',
          text: 'test_text',
          additionalText: 'test_additionalText',
          longText: 'test_longText',
          briefText: 'test_briefText',
          expandedTitle: 'test_expandedTitle',
        }
      },
      slotType:NotificationManager.SlotType.SOCIAL_COMMUNICATION
    }
    this.publishNotification(notificationRequest)
  }
  private publishMoreLongOrdinaryNotice = () => {
    let notificationRequest = {
      id: 2,
      content: {
        contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知
        multiLine: {
          title: 'test_title',
          text: 'test_text',
          briefText: 'test_briefText',
          longTitle: 'test_longTitle',
          lines: ['line_01', 'line_02', 'line_03', 'line_04'],
        }
      },
      slotType:NotificationManager.SlotType.SOCIAL_COMMUNICATION
    }
    this.publishNotification(notificationRequest)
  }
  private publishImageNotice = async () => {
    let rm = getContext(this).resourceManager;
    let file = await rm.getMediaContent($r('app.media.app_icon'))
    const pixel  = await image.createImageSource(file.buffer).createPixelMap()
    let imagePixelMap: PixelMap = pixel; // 需要获取图片PixelMap信息
    let notificationRequest: NotificationManager.NotificationRequest = {
      id: 3,
      content: {
        contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
        picture: {
          title: 'test_title',
          text: 'test_text',
          additionalText: 'test_additionalText',
          briefText: 'test_briefText',
          expandedTitle: 'test_expandedTitle',
          picture: imagePixelMap
        }
      },
      slotType:NotificationManager.SlotType.SOCIAL_COMMUNICATION
    };
    this.publishNotification(notificationRequest)
  }
  private publishDownNotice = (fileFullName) => {
    if (!this.isSupportTemplate) {
      promptAction.showToast({
        message: '不支持发送通知消息',
        duration: 2000,
      });
      return
    }
    let template = {
      name:'downloadTemplate',
      data: {
        title: '下载文件',
        fileName: fileFullName,
        progressValue: this.downFileProcess.receivedSize,
        progressMaxValue:this.downFileProcess.totalSize,
      }
    }
    //构造NotificationRequest对象
    let notificationRequest = {
      id: 999,
      slotType:NotificationManager.SlotType.SOCIAL_COMMUNICATION,
      template: template,
      content: {
        contentType: NotificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: template.data.title + template.data.fileName + this.downState,
          text: '',
          additionalText: ((this.downFileProcess.receivedSize / this.downFileProcess.totalSize) * 100).toFixed(2) + '%'
        }
      },
      deliveryTime: new Date().getTime(),
      showDeliveryTime: true,
    }
    this.publishNotification(notificationRequest)
  }
  private publishDownUI = (fileUrl: string, type: string) => {
    let context = getContext(this) as common.UIAbilityContext;
    const fileSuffixName = fileUrl.split('.')[fileUrl.split('.').length - 1]
    const fileFullName = fileUrl.split('/')[fileUrl.split('/').length - 1]
    console.log('context.filesDir', context.filesDir)
    const filePath = `${context.filesDir}${new Date().getTime() + '.' + fileSuffixName}`;
    this.setFileAddress = filePath
    try {
      request.downloadFile(context, { url: fileUrl,filePath: filePath }, (err, data) => {
        if (err) {
          console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
          return;
        }
        if (this.taskId) {
          clearInterval(this.taskId)
        }
        this.taskId = setInterval(() => {
          this.publishDownNotice(fileFullName)
        },10)
        // 监听文件下载的实时情况 receivedSize已下载 totalSize总大小
        data.on('progress', (receivedSize, totalSize) => {
          this.downState = DownloadState.DOWNLOADING
          console.info("upload totalSize:" + totalSize + "  receivedSize:" + receivedSize);
          this.downFileProcess = {
            totalSize: totalSize,
            receivedSize: receivedSize
          }
        })
        // 监听文件下载完成
        data.on('complete', () => {
          this.downState = DownloadState.FINISHED
          clearInterval(this.taskId)
          this.taskId = null
          this.publishDownNotice(fileFullName)
          console.info('Download task completed.');
        })
      });
    } catch (err) {
      console.error('err.code : ' + err.code + ', err.message : ' + err.message);
    }
  }
  build() {
    Column() {
      Button('发送普通文本类型通知')
        .onClick(this.publishOrdinaryNotice)
      Button('发送长文本类型通知')
        .onClick(this.publishLongOrdinaryNotice)
      Button('发送多行文本类型通知')
        .onClick(this.publishMoreLongOrdinaryNotice)
      Button('发送图片类型通知类型通知')
        .onClick(this.publishImageNotice)
      Button('发送下载类型通知')
        .onClick(() => {
          this.publishDownUI('https://xxx.com/1862578091974678528.mp4', 'test1')
        })
      Text('文件下载的真实进度条1')
      Progress({ value: this.downFileProcess.receivedSize, total: this.downFileProcess.totalSize, type: ProgressType.Linear }).width('90%')
      Text(`当前状态:${this.downState}`)
      Text('已下载:' + (this.downFileProcess.receivedSize / 1048576).toFixed(2) + 'MB')
      Text('总计:' + (this.downFileProcess.totalSize / 1048576).toFixed(2) + 'MB')
      Text('下载存储的位置' + this.setFileAddress)

      // Button('发送下载类型通知2')
      //   .onClick(() => {
      //     this.publishDownUI('https://kfxoss-biz-stg.oss-cn-hangzhou.aliyuncs.com/1698228608592657408.mp4', 'test2')
      //   })
    }
    .height('100%')
    .width('100%')
  }
}

上一章:HarmonyOS上传文件以及权限授权-CSDN博客

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐