Equivalent of iOS NSNotificationCenter in Android?

前端 未结 5 719
无人共我
无人共我 2021-01-31 05:51

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

5条回答
  •  一向
    一向 (楼主)
    2021-01-31 06:28

    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 observables;
    
        public ObservingService() {
            observables = new HashMap();
        }
    
        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);
            }
        }
    }
    

提交回复
热议问题