标签:
第一次使用是在Android中,broadcast。主要用在2个activity之间进行传递数据,发出一个广播,对这个广播有兴趣的就去监听它,做出相应的回应即可。主要是传递数据,触发机制比较好,跟全局变量或者单例有点像,但是使用场合有区别,比如2个activity之间传递数据,activity这种有生命周期的弄成全局变量和单例就不合适了。
发送广播:
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 来存放和提取数据
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]; }
使用字典来传递数据
老的版本的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的语法有点不同,本质是一样的。
http://www.waitingfy.com/archives/1692
标签:
原文地址:http://blog.csdn.net/fox64194167/article/details/45623011