HarmonyOS 鸿蒙Next中实现消息传递

发布于 1周前 作者 phonegap100 最后一次编辑是 5天前 来自 鸿蒙OS

HarmonyOS 鸿蒙Next中实现消息传递

介绍

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

概况

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

开始

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.pngScreenshot_20231208165404339.pngScreenshot_20231208165416940.png

公共事件代码

import commonEventManager from ‘@ohos.commonEventManager’;
import systemDateTime from ‘@ohos.systemDateTime’;

/**

*/ @Entry @Component struct CommonEventIndex {

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

private subscriberID

@State count: number = 0

aboutToAppear() {

<span class="hljs-keyword">let</span> subscribeInfo = {
  events: [<span class="hljs-string">"usual.event.TIME_TICK"</span>, <span class="hljs-string">'harvey.event.CUSTOM_1'</span>]
}

<span class="hljs-comment">// 创建订阅者回调</span>
commonEventManager.createSubscriber(subscribeInfo, (err, subscriber) =&gt; {
  <span class="hljs-keyword">if</span> (err) {
    console.error(`Failed to create subscriber. Code is ${err.code}, message is ${err.message}`);
    <span class="hljs-keyword">return</span>;
  }
  console.info(<span class="hljs-string">'Succeeded in creating subscriber.'</span> + <span class="hljs-built_in">JSON</span>.stringify(subscriber));

  <span class="hljs-keyword">this</span>.subscriberID = subscriber

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

}

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

build() {

Column(){
  Text(<span class="hljs-keyword">this</span>.mySubscriberInfo)
    .width(<span class="hljs-string">'100%'</span>)
    .fontColor(Color.Black)
    .fontSize(<span class="hljs-number">20</span>)
    .textAlign(TextAlign.Center)

  Button(<span class="hljs-string">'发布自定义公共事件'</span>).onClick(()=&gt;{

    <span class="hljs-keyword">let</span> option = {
      code: <span class="hljs-number">0</span>,
      data: <span class="hljs-built_in">JSON</span>.stringify({<span class="hljs-string">'hello'</span>: <span class="hljs-string">'word'</span>}),
      isOrdered: <span class="hljs-literal">true</span>,
      <span class="hljs-comment">// isSticky: true, 仅限系统应用&amp;服务</span>
      parameters: {
        <span class="hljs-string">'who'</span>: <span class="hljs-string">'am i'</span>,
        <span class="hljs-string">'count'</span>: <span class="hljs-keyword">this</span>.count++
      }
    }

    commonEventManager.publish(<span class="hljs-string">'harvey.event.CUSTOM_1'</span>, option, (error) =&gt; {
      console.log(<span class="hljs-built_in">JSON</span>.stringify(error))
    })
  })
}.width(<span class="hljs-string">'100%'</span>).height(<span class="hljs-string">'100%'</span>)

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

}

} <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

线程代码

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–

<span class="hljs-keyword">if</span>(<span class="hljs-keyword">this</span>.workerTotal == <span class="hljs-number">0</span>){
  Prompt.showToast({message: <span class="hljs-string">'8个任务已完成'</span>})
}

}

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

aboutToAppear() {

<span class="hljs-comment">// 处理来自worker线程的消息</span>
wk1.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(message)</span> {</span>
  console.log(<span class="hljs-string">"message from worker: "</span> + <span class="hljs-built_in">JSON</span>.stringify(message))
}

wk1.onmessage = (msg) =&gt; {

  <span class="hljs-keyword">if</span>(msg &amp;&amp; msg.data){
    <span class="hljs-keyword">if</span>(msg.data.no == <span class="hljs-number">1</span>){
      <span class="hljs-keyword">this</span>.worker1Color = Color.Green
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">this</span>.worker1Color = Color.Orange
    }
    <span class="hljs-keyword">this</span>.count()
  }

}

wk1.addEventListener(<span class="hljs-string">"message"</span>, (e)=&gt;{
  <span class="hljs-keyword">this</span>.workerData = <span class="hljs-built_in">JSON</span>.stringify(e)
  console.log(<span class="hljs-string">"message listener callback: "</span> + <span class="hljs-built_in">JSON</span>.stringify(e));
})

wk1.addEventListener(<span class="hljs-string">"WorkerTest"</span>, (e)=&gt;{
  <span class="hljs-keyword">this</span>.workerData = <span class="hljs-built_in">JSON</span>.stringify(e)
})

wk2.onmessage = (msg) =&gt; {
  <span class="hljs-keyword">if</span>(msg.data.no == <span class="hljs-number">2</span>){
    <span class="hljs-keyword">this</span>.worker2Color = Color.Green
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">this</span>.worker2Color = Color.Orange
  }
  <span class="hljs-keyword">this</span>.count()
}
wk3.onmessage = (msg) =&gt; {
  <span class="hljs-keyword">if</span>(msg.data.no == <span class="hljs-number">3</span>){
    <span class="hljs-keyword">this</span>.worker3Color = Color.Green
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">this</span>.worker3Color = Color.Orange
  }
  <span class="hljs-keyword">this</span>.count()
}
wk4.onmessage = (msg) =&gt; {
  <span class="hljs-keyword">if</span>(msg.data.no == <span class="hljs-number">4</span>){
    <span class="hljs-keyword">this</span>.worker4Color = Color.Green
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">this</span>.worker4Color = Color.Orange
  }
  <span class="hljs-keyword">this</span>.count()
}
wk5.onmessage = (msg) =&gt; {
  <span class="hljs-keyword">if</span>(msg.data.no == <span class="hljs-number">5</span>){
    <span class="hljs-keyword">this</span>.worker5Color = Color.Green
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">this</span>.worker5Color = Color.Orange
  }
  <span class="hljs-keyword">this</span>.count()
}
wk6.onmessage = (msg) =&gt; {
  <span class="hljs-keyword">if</span>(msg.data.no == <span class="hljs-number">6</span>){
    <span class="hljs-keyword">this</span>.worker6Color = Color.Green
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">this</span>.worker6Color = Color.Orange
  }
  <span class="hljs-keyword">this</span>.count()
}
wk7.onmessage = (msg) =&gt; {
  <span class="hljs-keyword">if</span>(msg.data.no == <span class="hljs-number">7</span>){
    <span class="hljs-keyword">this</span>.worker7Color = Color.Green
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">this</span>.worker7Color = Color.Orange
  }
  <span class="hljs-keyword">this</span>.count()
}
wk8.onmessage = (msg) =&gt; {
  <span class="hljs-keyword">if</span>(msg.data.no == <span class="hljs-number">8</span>){
    <span class="hljs-keyword">this</span>.worker8Color = Color.Green
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">this</span>.worker8Color = Color.Orange
  }
  <span class="hljs-keyword">this</span>.count()
}

<span class="hljs-keyword">let</span> innerEvent = {
  eventId: <span class="hljs-number">1847</span>
};

emitter.on(innerEvent, (eventData) =&gt; {
   <span class="hljs-keyword">this</span>.emitterData = process.tid + <span class="hljs-string">' '</span> + <span class="hljs-built_in">JSON</span>.stringify(eventData)
});

}

build() {

Column(){
  Text(<span class="hljs-string">'主线程ID: '</span> + process.tid)

  Text(<span class="hljs-keyword">this</span>.emitterData).fontSize(<span class="hljs-number">25</span>).textAlign(TextAlign.Center).margin({top: <span class="hljs-number">20</span>})

  Text(<span class="hljs-string">'发送 emitter 消息'</span>)
    .fontSize(<span class="hljs-number">20</span>)
    .fontColor(Color.White)
    .borderRadius(<span class="hljs-string">'12vp'</span>)
    .backgroundColor(Color.Blue)
    .padding(<span class="hljs-number">10</span>)
    .stateStyles({
      focused: {
        .backgroundColor(Color.Green)
      },
      pressed: {
        .backgroundColor(Color.Green)
      },
      normal: {
        .backgroundColor(Color.Blue)
      }
    })
    .onClick(()=&gt;{

        <span class="hljs-keyword">let</span> eventData = {
          data: {
            <span class="hljs-string">'count'</span>: <span class="hljs-keyword">this</span>.emitterCount++,
            <span class="hljs-string">'from'</span>: <span class="hljs-string">'emitter'</span>,
            <span class="hljs-string">"content"</span>: <span class="hljs-string">"c"</span>,
            <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
          }};
        <span class="hljs-keyword">let</span> innerEvent = {
          eventId: <span class="hljs-number">1847</span>,
          priority: emitter.EventPriority.HIGH
        };
        emitter.emit(innerEvent, eventData);

    })
    .margin({top: <span class="hljs-number">20</span>})

  Row(){
    Text(<span class="hljs-string">'1'</span>).fontSize(<span class="hljs-number">40</span>).backgroundColor(<span class="hljs-keyword">this</span>.worker1Color).fontColor(Color.White)
    Text(<span class="hljs-string">'2'</span>).fontSize(<span class="hljs-number">40</span>).backgroundColor(<span class="hljs-keyword">this</span>.worker2Color).fontColor(Color.White)
    Text(<span class="hljs-string">'3'</span>).fontSize(<span class="hljs-number">40</span>).backgroundColor(<span class="hljs-keyword">this</span>.worker3Color).fontColor(Color.White)
    Text(<span class="hljs-string">'4'</span>).fontSize(<span class="hljs-number">40</span>).backgroundColor(<span class="hljs-keyword">this</span>.worker4Color).fontColor(Color.White)
    Text(<span class="hljs-string">'5'</span>).fontSize(<span class="hljs-number">40</span>).backgroundColor(<span class="hljs-keyword">this</span>.worker5Color).fontColor(Color.White)
    Text(<span class="hljs-string">'6'</span>).fontSize(<span class="hljs-number">40</span>).backgroundColor(<span class="hljs-keyword">this</span>.worker6Color).fontColor(Color.White)
    Text(<span class="hljs-string">'7'</span>).fontSize(<span class="hljs-number">40</span>).backgroundColor(<span class="hljs-keyword">this</span>.worker7Color).fontColor(Color.White)
    Text(<span class="hljs-string">'8'</span>).fontSize(<span class="hljs-number">40</span>).backgroundColor(<span class="hljs-keyword">this</span>.worker8Color).fontColor(Color.White)
  }
  .width(<span class="hljs-string">'100%'</span>)
  .margin({top: <span class="hljs-number">20</span>})
  .justifyContent(FlexAlign.SpaceEvenly)

  Text(<span class="hljs-string">'Worker-postMessage'</span>)
    .fontSize(<span class="hljs-number">20</span>)
    .fontColor(Color.White)
    .borderRadius(<span class="hljs-string">'12vp'</span>)
    .backgroundColor(Color.Blue)
    .padding(<span class="hljs-number">10</span>)
    .stateStyles({
      focused: {
        .backgroundColor(Color.Green)
      },
      pressed: {
        .backgroundColor(Color.Green)
      },
      normal: {
        .backgroundColor(Color.Blue)
      }
    })
    .onClick(()=&gt;{
       <span class="hljs-keyword">this</span>.worker1Color = Color.Black
       <span class="hljs-keyword">this</span>.worker2Color = Color.Black
       <span class="hljs-keyword">this</span>.worker3Color = Color.Black
       <span class="hljs-keyword">this</span>.worker4Color = Color.Black
       <span class="hljs-keyword">this</span>.worker5Color = Color.Black
       <span class="hljs-keyword">this</span>.worker6Color = Color.Black
       <span class="hljs-keyword">this</span>.worker7Color = Color.Black
       <span class="hljs-keyword">this</span>.worker8Color = Color.Black

      <span class="hljs-keyword">let</span> tid = process.tid;

      console.log(<span class="hljs-string">'当前进程ID :'</span> + tid)

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

    })
    .margin({top: <span class="hljs-number">20</span>})

  Text(<span class="hljs-keyword">this</span>.workerData).fontSize(<span class="hljs-number">25</span>).textAlign(TextAlign.Center)

  Text(<span class="hljs-string">'Worker-dispatchEvent-自定义类型'</span>)
    .fontSize(<span class="hljs-number">20</span>)
    .fontColor(Color.White)
    .borderRadius(<span class="hljs-string">'12vp'</span>)
    .backgroundColor(Color.Blue)
    .padding(<span class="hljs-number">10</span>)
    .stateStyles({
      focused: {
        .backgroundColor(Color.Green)
      },
      pressed: {
        .backgroundColor(Color.Green)
      },
      normal: {
        .backgroundColor(Color.Blue)
      }
    })
    .onClick(()=&gt;{

      <span class="hljs-keyword">let</span> tid = process.tid;

      console.log(<span class="hljs-string">'当前进程ID :'</span> + tid)

      wk1.dispatchEvent({type: <span class="hljs-string">'WorkerTest'</span>, timeStamp: <span class="hljs-number">0</span>})

    })
    .margin({top: <span class="hljs-number">20</span>})

  Text(<span class="hljs-string">'Worker-dispatchEvent-message类型'</span>)
    .fontSize(<span class="hljs-number">20</span>)
    .fontColor(Color.White)
    .borderRadius(<span class="hljs-string">'12vp'</span>)
    .backgroundColor(Color.Blue)
    .padding(<span class="hljs-number">10</span>)
    .stateStyles({
      focused: {
        .backgroundColor(Color.Green)
      },
      pressed: {
        .backgroundColor(Color.Green)
      },
      normal: {
        .backgroundColor(Color.Blue)
      }
    })
    .onClick(()=&gt;{

      <span class="hljs-keyword">let</span> tid = process.tid;

      console.log(<span class="hljs-string">'当前进程ID :'</span> + tid)

      wk1.dispatchEvent({type: <span class="hljs-string">'message'</span>, timeStamp: <span class="hljs-number">0</span>})

    })
    .margin({top: <span class="hljs-number">20</span>})

}.width(<span class="hljs-string">'100%'</span>).height(<span class="hljs-string">'100%'</span>)
.justifyContent(FlexAlign.Center)

}

} <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

通过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)) } <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

在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’,
]
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
8 回复
UI线程里先定义
var workerInstance = new worker.ThreadWorker("entry/ets/data/Worker.ts");//每个app最多8个Worker

我在Worker.ts这个文件,线程里

workerPort.onmessage = function (e: MessageEvents) {

globalThis.data=new MyData()

}

new一个globalThis.的对象,比如说GlobalThis.data=new MyData()

然后发送消息

workerPort.postMessage({ type: 'message', value: 'mydata_start' });

然后UI线程接收消息

workerInstance.onmessage = function(e) {
// data:Worker线程发送的信息
let data = e.data;
if(data.value=='mydata_start') {
if (globalThis.data != undefined){
//do something

发现这里的globalThis.data还是undefine

globalThis不能跨线程么?

上述代码中,订阅、发送消息最终实现的效果,类似Android中Livedata的observeForever功能,即页面/组件在后台或被覆盖时,也会接收消息并处理相关逻辑。

我的问题是,在上述功能的基础上,如果想实现:

1、页面/组件在回到前台时,才接收消息并处理相关逻辑;

2、如果有多个订阅者,可以设置多个订阅者都接收信息,或者任意一个订阅者接收消息后,其他订阅者不能接收该消息;

3、数据版本控制。即发送端每个数据自带版本号,当发送端发送的数据,订阅者来不及处理时,下次订阅者仅处理最新版本数据。

以上功能,在Android端,我们使用Livedata实现,但在HarmonyOS上,请问该如何做?谢谢。

建议

  1. 用 TypeScript 实现一个订阅者模式工具(如:https://github.com/brendangoldberg/ts-livedata
  2. 十分了解UIAbility和Page的生命周期
  3. 实现自己的生命周期管理工具,或者等待下个HarmonyOS版本

感谢你的回复,我现在主要卡在生命周期这一步。 如果能在任意地方,简单便捷的获取ability及page的生命周期,后继的逻辑就方便很多,但现在没有办法实现。 我本来想试试能否hookability及page得到生命周期,但找了一圈资料,也没有找到相关解决方案。 所以目前来看,似乎只有等下个Harmony OS版本更新了。

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

这里设置了自动以监听,但是哪里调用了这个监听呢,wk1.dispatchEvent({type: 'WorkerTest', timeStamp: 0})这个dispatchEvent又是什么作用呢,不太理解。

我在主线程设置了监听,那么是在子线程是不是得有个地方调用"WorkerTest"它,就是回调的实现?

有个需求 要在主线程里面传入好多个监听,子线程里面设置一个while循环,然后依次给调起主线程中的监听器,主线程中的每个监听执行结束后再告诉子线程,然后子线程继续执行下调用下一个监听

HarmonyOS(鸿蒙)消息传递Next主要涉及系统内的通信机制优化与升级,旨在为用户提供更高效、安全的信息交互体验。在鸿蒙系统中,消息传递框架得到了全面重构,引入了更加灵活和强大的消息处理能力。

鸿蒙消息传递Next可能包括以下几个方面的改进:

  1. 高效传输:通过优化底层通信协议和传输算法,实现消息的快速、准确传递,降低延迟,提高系统响应速度。

  2. 安全增强:加强消息传输过程中的加密和验证机制,确保信息的安全性和隐私保护,防止数据泄露和篡改。

  3. 多设备协同:支持跨设备、跨平台的消息同步和共享,实现手机、平板、电视等智能设备之间的无缝连接和协同工作。

  4. 智能分发:根据用户的使用习惯和上下文环境,智能地分发和展示消息,提升用户体验。

  5. 扩展性:提供丰富的API和开发者工具,支持开发者快速接入和定制消息传递功能,满足不同应用场景的需求。

如果你在使用鸿蒙消息传递功能时遇到问题,可以尝试检查系统更新、重启设备或清理缓存等方法进行初步排查。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html。

回到顶部