If you think the Android project Gamework listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
package cz.robyer.gamework.game;
//fromwww.java2s.comimport java.util.WeakHashMap;
import cz.robyer.gamework.game.GameEvent.EventType;
import cz.robyer.gamework.utils.Log;
/**
* Handler for broadcasting {@link GameEvent}s.
* @author Robert P?sel
*/publicclass GameHandler implements GameEventBroadcaster {
privatestaticfinal String TAG = GameHandler.class.getSimpleName();
privatefinal WeakHashMap<GameEventListener, Boolean> listeners = new WeakHashMap<GameEventListener, Boolean>();
privatefinal GameService parent;
/**
* Class constructor.
* @param parent GameService which uses this handler.
*/public GameHandler(GameService parent) {
this.parent = parent;
}
/**
* Add listener.
* @param listener
* @return true if listener was added or false if it already existed
*/publicsynchronizedboolean addListener(GameEventListener listener) {
Log.d(TAG, "Adding GameEventListener " + listener.toString());
return (listeners.put(listener, true) == null);
}
/**
* Remove registered listener.
* @param listener to remove
* @return true when listener was removed or false if it did not existed
*/publicsynchronizedboolean removeListener(GameEventListener listener) {
Log.d(TAG, "Removing GameEventListener " + listener.toString());
return (listeners.remove(listener) != null);
}
/**
* Removes all registered listeners.
*/publicsynchronizedvoid clearListeners() {
Log.d(TAG, "Clearing GameEventListeners");
listeners.clear();
}
/**
* Broadcasts {@link GameEvent} to all registered listeners.
*/
@Override
publicsynchronizedvoid broadcastEvent(GameEvent event) {
int severity = android.util.Log.INFO;
if (event.type == EventType.UPDATED_LOCATION ||
event.type == EventType.UPDATED_TIME) {
severity = android.util.Log.DEBUG;
}
if (Log.loggingEnabled()) {
Log.println(severity, TAG, "Broadcasting event " + event.type.name() + " to " + listeners.size() + " listeners");
}
for (GameEventListener listener : listeners.keySet()) {
if (listener != null) {
listener.receiveEvent(event);
}
}
}
/**
* Broadcasts {@link GameEvent} to all registered listeners.
* @param type
*/publicsynchronizedvoid broadcastEvent(EventType type) {
broadcastEvent(new GameEvent(type));
}
/**
* Returns actual game time in milliseconds.
*/publiclong getGameTime() {
return parent.getTime();
}
}