Broadcast listening in Android ios cocos2d
1. About broadcast listening
The first use is in Android, broadcast. It is mainly used to transmit data between two activities and send a broadcast. If you are interested in this broadcast, you can listen to it and respond accordingly. It is mainly used to transmit data, and the trigger mechanism is better. It is a bit like a global variable or Singleton, but it is different in usage scenarios. For example, data is transmitted between two activities, it is not appropriate to create global variables and Singleton for activities with lifecycles.
2. Android Broadcast
Send broadcast:
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);
Listen to broadcast:
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)) { } } }
Use intent to store and extract data
3. IOS notifcenter Center
The names in IOS are different. They are used almost as follows:
Send Notification
NSDictionary *dictionary = [[NSDictionary alloc]init]; [[NSNotificationCenter defaultCenter] postNotificationName:@OUR_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE];
Listener:
[[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];}
Use dictionaries to transmit data
4. Custom events in cocos2d C ++
The old version of cocos2d is also named by notification, and the new version is changed.
Notification:
CustomClass retData;Director::getInstance()->getEventDispatcher()->dispatchCustomEvent(CbCC_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE, &retData);
Accept data:
_eventDispatcher->addCustomEventListener(CbCC_BLE_CENTRAL_MANAGER_NOTIFICAION_CHANGE_STATE, [this](EventCustom* event){ CustomClass *userData = (CustomClass *)event->getUserData(); });
You can use custom classes to transmit data.
Data can be transmitted between different Scene and Layer to trigger events. The syntax of Lua is a bit different, And the essence is the same.