HarmonyOS 消息传递

562 阅读5分钟

介绍

在HarmonyOS中,参考官方指导,其实你会发现在‘指南’和‘API参考’两个文档中,对消息传递使用的技术不是一对一的关系,那么今天这篇文章带你全面了解HarmonyOS 中的消息传递

概况

参照官方指导,我总结了两部分:1. 官方“指南”,即下图中的“Stage模型” 2. 总结的内容,即“消息事件” 消息事件传递技术.png

开始

EventHub

这个其实是可以帮大家解决几个最常见的消息传递场景:1. UIAbility和其它 2.页面和其它 3. 组件和其它

官方指导

样例

1. 订阅

this.context.eventHub.on('onConfigurationUpdate', (data) => {
    //订阅

});

2. 发送

let eventhub = this.context.eventHub;
eventhub.emit('onConfigurationUpdate', config);

3. 解除订阅

this.context.eventHub.off('onConfigurationUpdate')

CommonEvent

参照官方指南,其总称简写为CES(全称:Common Event Service),可以监听系统锁屏,时间变化,等等

1. 订阅

usual.event.TIME_TICK : 系统公共事件
harvey.event.CUSTOM_1 : 自定义事件

let subscribeInfo = {
  events: ["usual.event.TIME_TICK", 'harvey.event.CUSTOM_1']
}

// 1. 创建订阅者
commonEventManager.createSubscriber(subscribeInfo, (err, subscriber) => {
  if (err) {
    console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
    return;
  }
  console.info('Succeeded in creating subscriber.' + JSON.stringify(subscriber));

  this.subscriberID = subscriber

  // 2. 订阅事件回调
  commonEventManager.subscribe(subscriber, (err, commonEventData) => {
    if (err) {
      console.error(`Failed to subscribe common event. Code is ${err.code}, message is ${err.message}`);
      return;
    } else {
      systemDateTime.getCurrentTime(false, (error, data) => {
        this.mySubscriberInfo = data + '<=>' + JSON.stringify(commonEventData, null, '\t')
      })
    }
  })
})

2. 发送

对于系统级别的公共事件, 三方应用无权发送公共事件(即,即使你发送了,也是不会被收到的)
但是你可以自定义自己的公共事件

commonEventManager.publish('harvey.event.CUSTOM_1', option, (error) => {
  console.log(JSON.stringify(error))
})

3. 解除订阅

解除时用的是订阅者ID

commonEventManager.unsubscribe(this.subscriberID);

Emitter

1. 订阅

必须要有eventId, 这个代表消息的唯一标识

let innerEvent = {
  eventId: 1847
};

emitter.on(innerEvent, (eventData) => {
   this.emitterData = process.tid + ' ' + JSON.stringify(eventData)
});

2. 发送

let eventData = {
  data: {
    'count': this.emitterCount++,
    'from': 'emitter',
    "content": "c",
    "id": 1,
  }};
let innerEvent = {
  eventId: 1847,
  priority: emitter.EventPriority.HIGH
};
emitter.emit(innerEvent, eventData);

3. 解除订阅

emitter.off(1847)

Worker

1. 订阅

import worker from '@ohos.worker';

let wk1 = new worker.ThreadWorker("/entry/ets/workers/Worker.ts")

wk1.onmessage = (msg) => {

}

2. 发送

a)从worker线程中发送

import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';

var workerPort : ThreadWorkerGlobalScope = worker.workerPort;

workerPort.postMessage(
  {
    ......
  }
)

b) 从主线程中发送

wk1.dispatchEvent({type: 'message', timeStamp: 0})

3. 解除订阅

//第一种
wk1.off('message')
//第二种
wk1.removeEventListener('message')
//第三种:强制关闭线程
wk1..terminate()

TaskTool 和 Notification

总结

HarmonyOS是一个新系统,还是要实践才可能在真实的业务开发中灵活运用


实践代码效果

Screenshot_20231208165412224.png Screenshot_20231208165404339.png Screenshot_20231208165416940.png

公共事件代码

import commonEventManager from '@ohos.commonEventManager';
import systemDateTime from '@ohos.systemDateTime';

/**
 * https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/commoneventmanager-definitions-0000001493424344-V3#ZH-CN_TOPIC_0000001523808522__common_event_time_tick
 *
 */
@Entry
@Component
struct CommonEventIndex {

  @State mySubscriberInfo: string = '下一分钟会更新的'

  private subscriberID

  @State count: number = 0

  aboutToAppear() {

    let subscribeInfo = {
      events: ["usual.event.TIME_TICK", 'harvey.event.CUSTOM_1']
    }

    // 创建订阅者回调
    commonEventManager.createSubscriber(subscribeInfo, (err, subscriber) => {
      if (err) {
        console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
        return;
      }
      console.info('Succeeded in creating subscriber.' + JSON.stringify(subscriber));

      this.subscriberID = subscriber

      // 订阅公共事件回调
      commonEventManager.subscribe(subscriber, (err, commonEventData) => {
        if (err) {
          console.error(`Failed to subscribe common event. Code is ${err.code}, message is ${err.message}`);
          return;
        } else {
          systemDateTime.getCurrentTime(false, (error, data) => {
            this.mySubscriberInfo = data + '<=>' + JSON.stringify(commonEventData, null, '\t')
          })
        }
      })
    })

  }

  aboutToDisappear(){
    commonEventManager.unsubscribe(this.subscriberID);
  }

  build() {

    Column(){
      Text(this.mySubscriberInfo)
        .width('100%')
        .fontColor(Color.Black)
        .fontSize(20)
        .textAlign(TextAlign.Center)

      Button('发布自定义公共事件').onClick(()=>{

        let option = {
          code: 0,
          data: JSON.stringify({'hello': 'word'}),
          isOrdered: true,
          // isSticky: true, 仅限系统应用&服务
          parameters: {
            'who': 'am i',
            'count': this.count++
          }
        }

        commonEventManager.publish('harvey.event.CUSTOM_1', option, (error) => {
          console.log(JSON.stringify(error))
        })
      })
    }.width('100%').height('100%')

    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)

  }


}

线程代码

import emitter from '@ohos.events.emitter'
import worker from '@ohos.worker';
import process from '@ohos.process';
import Prompt from '@system.prompt';

/**
 * 依据官方指导,最多只能创建8个worker
 *
 */
let wk1 = new worker.ThreadWorker("/entry/ets/workers/Worker.ts")
let wk2 = new worker.ThreadWorker("/entry/ets/workers/Worker2.ts")
let wk3 = new worker.ThreadWorker("/entry/ets/workers/Worker3.ts")
let wk4 = new worker.ThreadWorker("/entry/ets/workers/Worker4.ts")
let wk5 = new worker.ThreadWorker("/entry/ets/workers/Worker5.ts")
let wk6 = new worker.ThreadWorker("/entry/ets/workers/Worker6.ts")
let wk7 = new worker.ThreadWorker("/entry/ets/workers/Worker7.ts")
let wk8 = new worker.ThreadWorker("/entry/ets/workers/Worker8.ts")


@Entry
@Component
struct ThreadModelIndex {

  @State emitterData: string = ''
  emitterCount: number = 0

  @State worker1Color: number = 0
  @State worker2Color: number = 0
  @State worker3Color: number = 0
  @State worker4Color: number = 0
  @State worker5Color: number = 0
  @State worker6Color: number = 0
  @State worker7Color: number = 0
  @State worker8Color: number = 0

  @State workerData: string = ''

  workerTotal: number = 8;

  async count() {
    this.workerTotal--

    if(this.workerTotal == 0){
      Prompt.showToast({message: '8个任务已完成'})
    }

  }

  aboutToDisappear(){
    wk1.terminate()
    wk2.terminate()
    wk3.terminate()
    wk4.terminate()
    wk5.terminate()
    wk6.terminate()
    wk7.terminate()
    wk8.terminate()
  }

  aboutToAppear() {

    // 处理来自worker线程的消息
    wk1.onmessage = function(message) {
      console.log("message from worker: " + JSON.stringify(message))
    }

    wk1.onmessage = (msg) => {

      if(msg && msg.data){
        if(msg.data.no == 1){
          this.worker1Color = Color.Green
        } else {
          this.worker1Color = Color.Orange
        }
        this.count()
      }

    }

    wk1.addEventListener("message", (e)=>{
      this.workerData = JSON.stringify(e)
      console.log("message listener callback: " + JSON.stringify(e));
    })

    wk1.addEventListener("WorkerTest", (e)=>{
      this.workerData = JSON.stringify(e)
    })

    wk2.onmessage = (msg) => {
      if(msg.data.no == 2){
        this.worker2Color = Color.Green
      } else {
        this.worker2Color = Color.Orange
      }
      this.count()
    }
    wk3.onmessage = (msg) => {
      if(msg.data.no == 3){
        this.worker3Color = Color.Green
      } else {
        this.worker3Color = Color.Orange
      }
      this.count()
    }
    wk4.onmessage = (msg) => {
      if(msg.data.no == 4){
        this.worker4Color = Color.Green
      } else {
        this.worker4Color = Color.Orange
      }
      this.count()
    }
    wk5.onmessage = (msg) => {
      if(msg.data.no == 5){
        this.worker5Color = Color.Green
      } else {
        this.worker5Color = Color.Orange
      }
      this.count()
    }
    wk6.onmessage = (msg) => {
      if(msg.data.no == 6){
        this.worker6Color = Color.Green
      } else {
        this.worker6Color = Color.Orange
      }
      this.count()
    }
    wk7.onmessage = (msg) => {
      if(msg.data.no == 7){
        this.worker7Color = Color.Green
      } else {
        this.worker7Color = Color.Orange
      }
      this.count()
    }
    wk8.onmessage = (msg) => {
      if(msg.data.no == 8){
        this.worker8Color = Color.Green
      } else {
        this.worker8Color = Color.Orange
      }
      this.count()
    }

    let innerEvent = {
      eventId: 1847
    };

    emitter.on(innerEvent, (eventData) => {
       this.emitterData = process.tid + ' ' + JSON.stringify(eventData)
    });

  }


  build() {

    Column(){
      Text('主线程ID: ' + process.tid)

      Text(this.emitterData).fontSize(25).textAlign(TextAlign.Center).margin({top: 20})

      Text('发送 emitter 消息')
        .fontSize(20)
        .fontColor(Color.White)
        .borderRadius('12vp')
        .backgroundColor(Color.Blue)
        .padding(10)
        .stateStyles({
          focused: {
            .backgroundColor(Color.Green)
          },
          pressed: {
            .backgroundColor(Color.Green)
          },
          normal: {
            .backgroundColor(Color.Blue)
          }
        })
        .onClick(()=>{

            let eventData = {
              data: {
                'count': this.emitterCount++,
                'from': 'emitter',
                "content": "c",
                "id": 1,
              }};
            let innerEvent = {
              eventId: 1847,
              priority: emitter.EventPriority.HIGH
            };
            emitter.emit(innerEvent, eventData);

        })
        .margin({top: 20})

      Row(){
        Text('1').fontSize(40).backgroundColor(this.worker1Color).fontColor(Color.White)
        Text('2').fontSize(40).backgroundColor(this.worker2Color).fontColor(Color.White)
        Text('3').fontSize(40).backgroundColor(this.worker3Color).fontColor(Color.White)
        Text('4').fontSize(40).backgroundColor(this.worker4Color).fontColor(Color.White)
        Text('5').fontSize(40).backgroundColor(this.worker5Color).fontColor(Color.White)
        Text('6').fontSize(40).backgroundColor(this.worker6Color).fontColor(Color.White)
        Text('7').fontSize(40).backgroundColor(this.worker7Color).fontColor(Color.White)
        Text('8').fontSize(40).backgroundColor(this.worker8Color).fontColor(Color.White)
      }
      .width('100%')
      .margin({top: 20})
      .justifyContent(FlexAlign.SpaceEvenly)

      Text('Worker-postMessage')
        .fontSize(20)
        .fontColor(Color.White)
        .borderRadius('12vp')
        .backgroundColor(Color.Blue)
        .padding(10)
        .stateStyles({
          focused: {
            .backgroundColor(Color.Green)
          },
          pressed: {
            .backgroundColor(Color.Green)
          },
          normal: {
            .backgroundColor(Color.Blue)
          }
        })
        .onClick(()=>{
           this.worker1Color = Color.Black
           this.worker2Color = Color.Black
           this.worker3Color = Color.Black
           this.worker4Color = Color.Black
           this.worker5Color = Color.Black
           this.worker6Color = Color.Black
           this.worker7Color = Color.Black
           this.worker8Color = Color.Black

          let tid = process.tid;

          console.log('当前进程ID :' + tid)

          // 发送消息到worker线程
          wk1.postMessage({'no':1,'threadID': tid,  'costtime': 1000})
          wk2.postMessage({'no':2,'threadID': tid, 'costtime': 1500})
          wk3.postMessage({'no':3,'threadID': tid, 'costtime': 2000})
          wk4.postMessage({'no':4,'threadID': tid, 'costtime': 2500})
          wk5.postMessage({'no':5,'threadID': tid, 'costtime': 3000})
          wk6.postMessage({'no':6,'threadID': tid, 'costtime': 3500})
          wk7.postMessage({'no':7,'threadID': tid, 'costtime': 4000})
          wk8.postMessage({'no':8,'threadID': tid, 'costtime': 4500})

        })
        .margin({top: 20})

      Text(this.workerData).fontSize(25).textAlign(TextAlign.Center)

      Text('Worker-dispatchEvent-自定义类型')
        .fontSize(20)
        .fontColor(Color.White)
        .borderRadius('12vp')
        .backgroundColor(Color.Blue)
        .padding(10)
        .stateStyles({
          focused: {
            .backgroundColor(Color.Green)
          },
          pressed: {
            .backgroundColor(Color.Green)
          },
          normal: {
            .backgroundColor(Color.Blue)
          }
        })
        .onClick(()=>{

          let tid = process.tid;

          console.log('当前进程ID :' + tid)

          wk1.dispatchEvent({type: 'WorkerTest', timeStamp: 0})

        })
        .margin({top: 20})

      Text('Worker-dispatchEvent-message类型')
        .fontSize(20)
        .fontColor(Color.White)
        .borderRadius('12vp')
        .backgroundColor(Color.Blue)
        .padding(10)
        .stateStyles({
          focused: {
            .backgroundColor(Color.Green)
          },
          pressed: {
            .backgroundColor(Color.Green)
          },
          normal: {
            .backgroundColor(Color.Blue)
          }
        })
        .onClick(()=>{

          let tid = process.tid;

          console.log('当前进程ID :' + tid)

          wk1.dispatchEvent({type: 'message', timeStamp: 0})

        })
        .margin({top: 20})

    }.width('100%').height('100%')
    .justifyContent(FlexAlign.Center)

  }

}

通过IDEWorker模板创模板下文件(参见:指导
Worker.ts, Worker2.ts, Worker3.ts, Worker4.ts, Worker5.ts, Worker6.ts, Worker7.ts, Worker8.ts
这些文件内容完全一样,仅仅是名称不一样

import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';
import Logger from '../common/Logger';
import process from '@ohos.process';
import emitter from '@ohos.events.emitter'

var workerPort : ThreadWorkerGlobalScope = worker.workerPort;

/**
* Defines the event handler to be called when the worker thread receives a message sent by the host thread.
* The event handler is executed in the worker thread.
*
* @param e message data
*/
workerPort.onmessage = function(e : MessageEvents) {
  let tid = process.tid;

  Logger.d(tid + ' worker收到了消息 : ' + JSON.stringify(e))

  setTimeout(()=>{
    workerPort.postMessage(
      {
        'no': (e.data.no),
        'threadID' : tid + '-' + e.data.threadID,
        'label': "worker",
      }
    )
  }, e.data.costtime)

  let eventData = {
    data: {
      'threadID' : tid + '-' + e.data.threadID,
      'from': 'emitter',
      "content": "c",
      "id": 1,
    }};
  let innerEvent = {
    eventId: 1847,
    priority: emitter.EventPriority.HIGH
  };
  emitter.emit(innerEvent, eventData);

}

/**
* Defines the event handler to be called when the worker receives a message that cannot be deserialized.
* The event handler is executed in the worker thread.
*
* @param e message data
*/
workerPort.onmessageerror = function(e : MessageEvents) {
  Logger.d(JSON.stringify(e))
}

/**
* Defines the event handler to be called when an exception occurs during worker execution.
* The event handler is executed in the worker thread.
*
* @param e error message
*/
workerPort.onerror = function(e : ErrorEvent) {
  Logger.d(JSON.stringify(e))
}

在Build-profile.json5需要添加如上TS

"buildOption": {
  "sourceOption": {
    "workers": [
      './src/main/ets/workers/worker.ts',
      './src/main/ets/workers/worker2.ts',
      './src/main/ets/workers/worker3.ts',
      './src/main/ets/workers/worker4.ts',
      './src/main/ets/workers/worker5.ts',
      './src/main/ets/workers/worker6.ts',
      './src/main/ets/workers/worker7.ts',
      './src/main/ets/workers/worker8.ts',
      './src/main/ets/workers/worker9.ts',
    ]
  }
}