ios有android广播吗,关于 Android ios cocos2d 中的广播监听

本文探讨了在Android、iOS和Cocos2d-C++中实现跨组件通信的广播通知机制。在Android中,通过Intent发送和接收广播;iOS使用NotificationCenter发布和监听通知;Cocos2d-C++则采用自定义事件进行数据传递。这些机制在不同场景下用于活动间的数据传输和事件触发,提供了灵活的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 关于广播监听

第一次使用是在Android中,broadcast。主要用在2个activity之间进行传递数据,发出一个广播,对这个广播有兴趣的就去监听它,做出相应的回应即可。主要是传递数据,触发机制比较好,跟全局变量或者单例有点像,但是使用场合有区别,比如2个activity之间传递数据,activity这种有生命周期的弄成全局变量和单例就不合适了。

2.Android的广播

发送广播:

Intent intent = new Intent("OUR_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE");

intent.putExtra("KEY_OLD_STATE", oldState);

intent.putExtra("KEY_NEW_STATE", newState);

mContext.sendBroadcast(intent);

监听广播:private void registerBleBroadcastReceiver()

{

IntentFilter intentFilter = new IntentFilter();

intentFilter.addAction("OUR_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE");

this.mContext.registerReceiver(mBleBroadcastReceiver, intentFilter);

}

private BleBroadcastReceiver mBleBroadcastReceiver;

private class BleBroadcastReceiver extends BroadcastReceiver

{

@Override

public void onReceive(Context context, Intent intent)

{

String action = intent.getAction();

if (action.equals("OUR_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE"))

{

}

}

}

通过intent 来存放和提取数据

3. IOS NotificationCenter

IOS中的名字不一样,使用起来差不多:

发送Notification

NSDictionary *dictionary = [[NSDictionary alloc]init];

[[NSNotificationCenter defaultCenter] postNotificationName:@"OUR_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE"];

监听:

[[NSNotificationCenter defaultCenter] addObserver:cmIos selector:@selector(bleCenterManagerNotificationChangeState:) name:@"OUR_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE" object:nil];

-(void)bleCenterManagerNotificationChangeState:(NSNotification*)value

{

log("bleCenterManagerNotificationChangeState");

NSDictionary *dictionary = [value object];

NSNumber *oldState = [dictionary objectForKey:KEY_OLD_STATE];

NSNumber *newState = [dictionary objectForKey:KEY_NEW_STATE];

}

使用字典来传递数据

4. cocos2d C++中的自定义事件

老的版本的cocos2d也是用notification命名的,新的改了。

发生通知:

CustomClass retData;

Director::getInstance()->getEventDispatcher()->dispatchCustomEvent("CbCC_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE", &retData);

接受数据:

_eventDispatcher->addCustomEventListener("CbCC_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE", [this](EventCustom* event){

CustomClass *userData = (CustomClass *)event->getUserData();

});

可以通过自定义类来传递数据。

可以方便在不同的Scene,Layer之间进行传递数据,触发事件。Lua的语法有点不同,本质是一样的。

Post Views: 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值