鸿蒙---应用通知/数据库

242 阅读3分钟

鸿蒙---应用通知/数据库


本篇记录中涉及应用通知,公共事件,数据库三方面。

首先上篇再下载中,有提到开启状态栏通知,先看下应用本地通知的构建。

通知

通过notificationManager发布通知

notificationManager.publish(request)

下面看下各种常见通知的构建。

  1. 普通文本通知

    • 创建通知意图
      let agent = {
      wants: [
        {
          deviceId: '', // 为空 表示本设备
          bundleName: 'com.example.oneapplication', // 包名
          abilityName: 'MainAbility' // 启动的Ability名
        }
      ],
      operationType: wantAgent.OperationType.START_ABILITY,
      requestCode: 0,
      wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
    }
    let info = await wantAgent.getWantAgent(agent)
    
    • 构建通知请求
      let request = {
      id: 1,
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: 'title title',
          text: 'text text'
        }
      },
      wantAgent: info // 点击跳转意图
    }
    
  2. 多行文本通知

      let request = {
      id: 1,
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE,
        multiLine: {
          title: 'title title',
          text: 'text text',
          briefText: 'tttt',  // 通知概要内容
          longTitle: 'title',  // 展开时的标题
          lines: ['aaa','bbb','ccc']
        }
      }
    }
    
  3. 带图片通知

    • 构建图片PixelMap
      const context = getContext(this)
      const resourceManager = context.resourceManager
      // 读取本地media图片资源
      let fileData = await resourceManager.getMediaContent($r('app.media.ad'))
      let buf = fileData.buffer
    
      const imageSource = image.createImageSource(buf)
      let decodingOptions = {
        editable: true,  // 是否可编辑
        desiredPixelFormat: image.PixelMapFormat.RGBA_8888 // 图片像素格式
      }
    
      let pixelMap = await imageSource.createPixelMap(decodingOptions)
    
    • 构建图片通知请求
      let request = {
      id: 1,
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
        picture: {
          title: 'title title',
          text: 'text text',
          expandedTitle: 'expand title',
          additionalText: 'aaa',  // 附加内容
          briefText: 'bbbb',  // 概要内容
          picture: pixelMap         // 图片 数据
        }
      }
    }
    
  4. 进度模板通知

    • 判断是否支持模板
      notificationManager.isSupportTemplate('downloadTemplate').then(isSupport => {
      if (isSupport) {
        // 支持模板 发送通知
        notificationManager.publish(request)
      }
    })
    
    • 构建进度模板
      let template = {
      name: 'downloadTemplate',
      data: {
        title: 'title',
        fileName: 'test.apk',
        progressValue: 30,
        progressMaxValue: 100
      }
    }
    
    • 构建通知请求
      let request = {
      id: 1,
      slotType: notificationManager.SlotType.OTHER_TYPES,
      template: template,
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: 'title title',
          text: 'text text'
        }
      },
      deliveryTime: new Date().getTime(),
      showDeliveryTime: true  // 显示分发时间
    }
    

还有很多诸如长文本通知,开启声音震动提醒,清除通知,通知按钮等情况就不在这里一一展示了。

公共事件

在通知中携带的意图可以触发发送公共事件,这里顺带也看了下。

  1. 通知触发公共事件
       let agent = {
       wants: [
         {
           action: 'event_name',
           parameters: {
             name: 'aaaaa'
           }
         }
       ],
       operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
       requestCode: 0,
       wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
     }
     let info = await wantAgent.getWantAgent(agent)
    
  2. 主动发送
     let options = {
      code: 1,
      data: 'aaaa',
      isOrdered: true
    }
    commonEventManager.publish('event_name',options,() => {
    
    })
    
  3. 事件订阅
    commonEventManager.createSubscriber({
      events: ['event_name']
    }).then(data => {
      commonEventManager.subscribe(data,(err,eventData) => {
        if (!err) {
          console.log('get event::',eventData.parameters)
        }
      })
    })
    

静态订阅仅对系统应用开放,这里就不记录了。系统拥有的公共事件能力

数据库存储

关于鸿蒙数据持久化中,再第一篇中有涉及到用户首选项,上一篇中也有文件相关API。 再这一篇中,将记录数据库存储。

鸿蒙中数据库存储分为键值型数据库实现(存储键值对形式的数据) 及关系型数据库实现(基于SQLite组件,适用于存储包含复杂关系数据的场景)。

键值型数据库
  1. 初始化
    this.manager = distributedKVStore.createKVManager({
      bundleName: 'com.example.oneapplication',
      context: getContext(this)
    })
    
    this.store = await this.manager.getKVStore('kvTest',{
      createIfMissing: true, // 数据库不存在时,进行创建  默认创建
      encrypt: false,  // 是否加密存储  默认不加密
      backup: false,  // 是否备份  默认备份
      kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,  // 数据库类型,默认多设备协同数据库
      securityLevel: distributedKVStore.SecurityLevel.S2 // 安全级别
    })
    
      
    // 关闭数据库
    this.manager.closeKVStore('com.example.oneapplication', 'kvTest')
    
  2. 存储
    this.store.put(key,'123').then(() => {
    
    }).catch(err => {
      console.log('store put err:',err)
    })
    
  3. 获取
    this.store.get(key).then(value => {
      console.log('store put value:',value)
    }).catch(err => {
      console.log('store get err:',err)
    })
    
  4. 删除
    this.store.delete(key).then(() => {
      console.log('store del suc:')
    }).catch(err => {
      console.log('store del err:',err)
    })
    
关系型数据库
  1. 初始化 建表
    this.store = await relationalStore.getRdbStore(getContext(this),{
      name: 'oneTest.db',
      securityLevel: relationalStore.SecurityLevel.S2
    })
    
    const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT,' +
    'NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)';
    
    this.store.executeSql(SQL_CREATE_TABLE) // 执行SQL语句 创建表
    
  2. 新增
    this.store.insert('EMPLOYEE',{
      'NAME': 'test',
      'AGE': 18,
      'SALARY': 10.23,
      'CODES': new Uint8Array([1,2,3,4])
    }).then(rowId => {
      console.log('insert data::',rowId)
    }).catch(err => {
      console.log('insert error::',err)
    })
    
  3. 修改
    // 创建修改条件
    const predicates = new relationalStore.RdbPredicates('EMPLOYEE')
    predicates.equalTo('NAME', 'test')
    
    this.store.update({
      'SALARY': 568.2
    },predicates).then(rowId => {
      console.log('update data::',rowId)
    }).catch(err => {
      console.log('update error::',err)
    })
    
  4. 删除
    const predicates = new relationalStore.RdbPredicates('EMPLOYEE')
    predicates.equalTo('NAME', 'test')
    // 删除NAME为test的数据
    this.store.delete(predicates).then(rowId => {
      console.log('delete data::',rowId)
    }).catch(err => {
      console.log('delete error::',err)
    })
    
  5. 查询
      // 查询条件
    const predicates = new relationalStore.RdbPredicates('EMPLOYEE')
    // predicates.equalTo('NAME', 'test')
    
    this.store.query(predicates,['ID','NAME','CODES','SALARY','AGE']).then(result => {
      let isResult = result.goToFirstRow()  // 转到结果集第一行
      while (isResult) { // 有结果集
        let id = result.getLong(0)
        let name = result.getString(1)
        let codes = result.getBlob(2)
        let salary = result.getDouble(3)
        let age = result.getLong(4)
        console.log('query data::',id,name,codes,salary,age)
        isResult = result.goToNextRow()
      }
    }).catch(err => {
      console.log('query error::',err)
    })