Is there an equivalent of the iOS class NSNotificationCenter in Android ? Are there any libraries or useful code available to me ?
A notification center can deliver notifications only within a single program; if you want to post a notification to other processes or receive notifications from other processes, use NSDistributedNotificationCenter instead.
Objects register with a notification center to receive notifications ( NSNotification objects) using the addObserver:selector:name:object: or addObserverForName:object:queue:usingBlock: methods. When an object adds itself as an observer, it specifies which notifications it should receive.
An object may therefore call this method several times in order to register itself as an observer for several different notifications. Each running app has a defaultCenter notification center, and you can create new notification centers to organize communications in particular contexts.
Each running app has a defaultCenter notification center, and you can create new notification centers to organize communications in particular contexts.
In Android there is not a central notification center as in ios. But you can basically use Observable and Observer objects to achieve your task.
You can define a class like something below, just modify it for singleton use and add synchronized for concurrent use but the idea is the same:
public class ObservingService {
HashMap<String, Observable> observables;
public ObservingService() {
observables = new HashMap<String, Observable>();
}
public void addObserver(String notification, Observer observer) {
Observable observable = observables.get(notification);
if (observable==null) {
observable = new Observable();
observables.put(notification, observable);
}
observable.addObserver(observer);
}
public void removeObserver(String notification, Observer observer) {
Observable observable = observables.get(notification);
if (observable!=null) {
observable.deleteObserver(observer);
}
}
public void postNotification(String notification, Object object) {
Observable observable = observables.get(notification);
if (observable!=null) {
observable.setChanged();
observable.notifyObservers(object);
}
}
}
Take a look at the Otto event bus from Square:
http://square.github.com/otto/
It has essentially the same features as NSNotificationCenter but thanks to annotations and static typing it is easier to follow the dependencies of components and paths that events follow. It's much simpler to use than the stock Android broadcast API, IMO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With