Equivalent of iOS NSNotificationCenter in Android?

android, ios, iphone

Solution

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);
        }
    }
}

Problem

Is there an equivalent of the iOS class NSNotificationCenter in Android ? Are there any libraries or useful code available to me ?

Original source

Related problems