简介
my.navigatetominiprogram 和 my.openembededminiprogram 具备通信功能,在调用方与被启动的小程序之间建立了通信通道,允许双方互发消息。
要使用小程序间通信通道,请确保小程序基础库版本为 2.9.41 及以上。通过以下方式可快速判定该能力是否已经支持:
my.caniuse('navigatetominiprogram.return.eventchannel')
通信通道
应用间通信通道对象与页面间通信通道对象都采用了 eventchannel 接口,可以像使用 my.navigateto 那样去使用新能力:
my.navigatetominiprogram({
appid: 'app_id',
events: {
acceptdatafromopenedapp(data) {
console.log(data);
},
},
success(res) {
const { eventchannel } = res;
if (eventchannel) {
eventchannel.emit('acceptdatafromopenerapp', {
data: 'from opener app',
});
}
},
})
对于被启动的小程序,可以通过 app.onlaunch 等方式拿到通信通道的一端。值得注意的是,app.onlaunch 和 app.onshow 有两个对等的全局 api,分别是 my.getlaunchoptionssync 和 my.getenteroptionssync。
app({
onlaunch(options) {
// options 等同于调用 my.getlaunchoptionssync
getlaunchorenteroptionscallback(options);
},
onshow(options) {
// options 等同于调用 my.getenteroptionssync
getlaunchorenteroptionscallback(options);
},
});
function getlaunchorenteroptionscallback(options) {
// 当小程序被另一应用启动时可获得此对象
if (options.eventchannel) {
eventchannel.on('acceptdatafromopenerapp', (message) => {
console.log(message);
});
eventchannel.emit('acceptdatafromopenedapp', {
data: 'from opened app',
});
} else {
// 小程序不是被其他应用启动
}
}
热启动和冷启动
小程序有两种启动方式:热启动和冷启动。
- 在被启动的小程序的整个生命周期中,随时可以通过 my.getlaunchoptionssync 获得冷启动了自身的小程序的通信通道;
- 而被保活唤起时,取决于唤起方是否通过 my.navigatetominiprogram 能力,被打开的小程序的 my.getenteroptionssync 返回对象中可能存在 eventchannel 对象。
- my.getenteroptionssync 的返回结果等同于 app.onshow 生命周期的入参。当小程序被压后台并重新回到前台时,会触发该生命周期,也会变更 my.getenteroptionssync 的返回结果。此种场景下没有 eventchannel 对象。
注意:每次启动都可能产生全新的通信通道。这些通道之间的数据并不共享,请注意区分。
区分通道源
对于被启动的小程序,可以通过 eventchannel.source 获得将自身启动的小程序的 appid。
const { eventchannel } = my.getlaunchoptionssync();
if (eventchannel) {
console.log(eventchannel.source);
}
小程序重启
当被启动的小程序自身调用了 my.restartminiprogram 后,伴随小程序的重启,通信通道并不会失效,但被打开侧的通信通道将被完全刷新。此时,请注意被打开的小程序可能重复通信。