我有三个 Ionic 5 应用程序。如果我打开第一个应用程序并且其他两个应用程序中的任何一个在后台运行,我需要发送一些数据,但前提是第二个应用程序存在于后台。
我目前正在尝试使用 Cordova Broadcaster 插件 (https://github.com/bsorrentino/cordova-broadcaster)。虽然我已成功地从第一个应用程序调用发送函数,但我遇到了第二个应用程序未收到广播的问题。
发送者应用程序代码(单击按钮即可调用):-
import { Broadcaster } from '@awesome-cordova-plugins/broadcaster/ngx';
constructor( private broadcaster :Broadcaster){}
sendFunction(){
let options1 = {"sample":"data"};
if (this.platform.is('android') && this.platform.is('capacitor')) {
var isGlobal = true
this.broadcaster.fireNativeEvent("SOR_APPS_TOKEN", isGlobal, options1).then(res => {
console.log("event fired!");
})
}
}
接收器应用程序代码:-
import { Broadcaster } from '@awesome-cordova-plugins/broadcaster/ngx';
constructor( private broadcaster :Broadcaster){}
onInit(){
if (this.platform.is('android') && this.platform.is('capacitor')) {
console.log( "register didShow received!" );
let listener = function( e ) {
console.log( "SOR_APPS_TOKEN received! userInfo: " + JSON.stringify(e) );
}
this.broadcaster.addEventListener( "SOR_APPS_TOKEN").subscribe( listener );
}
}
在我添加的清单文件中(用于广播接收应用程序):-
<receiver android:name="SOR_APPS_TOKEN" >
<intent-filter>
<action android:name="com.example.app1" >
</action>
</intent-filter>
</receiver>
附注GitHub 上任何说明此功能的示例应用程序将不胜感激。
更新:-
这是我尝试过的其他选项的链接(也不起作用):- https://github.com/bsorrentino/cordova-broadcaster/issues/72
我能够使用 Ionic webIntent 解决该问题 (https://www.npmjs.com/package/@ionic-native/web-intent)
来自应用程序 1(位于前台):-
try {
let extraName="TEST_DATA";
this.webIntent.sendBroadcast({
action: 'com.test.app1.APPS_BROADCAST',
extras: {
[extraName]: 'TEST_DATA_3',
"SEND_RESULT": 'TEST_DATA_4'
}
});
} catch (e) {
console.log("Error in sending broadcast ", e);
}
并在应用程序 2(在后台)中将接收器注册为:-
try{
this.webIntent.registerBroadcastReceiver({
filterActions: [
// 'com.darryncampbell.cordova.plugin.broadcastIntent.ACTION',
'com.test.app1.APPS_BROADCAST
],
filterCategories: [
'android.intent.category.DEFAULT'
]
}).subscribe((intent) => {
console.log('================== this.webIntent.registerBroadcastReceiverReceived Intent: ' + JSON.stringify(intent));
});
}catch(e){
console.log("========= this.webIntent.registerBroadcastReceiver Error in registering broadcast receiver",e);
}