Equivalent of iOS NSNotificationCenter in Android?

前端 未结 5 718
无人共我
无人共我 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:18

    i had the same wondrings.. so i wrote this:

    public class NotificationCenter {
    
        //static reference for singleton
        private static NotificationCenter _instance;
    
        private HashMap> registredObjects;
    
        //default c'tor for singleton
        private NotificationCenter(){
            registredObjects = new HashMap>();
        }
    
        //returning the reference
        public static synchronized NotificationCenter defaultCenter(){
            if(_instance == null)
                _instance = new NotificationCenter();
            return _instance;
        }
    
        public synchronized void addFucntionForNotification(String notificationName, Runnable r){
            ArrayList list = registredObjects.get(notificationName);
            if(list == null) {
                list = new ArrayList();
                registredObjects.put(notificationName, list);
            }
            list.add(r);
        }
    
        public synchronized void removeFucntionForNotification(String notificationName, Runnable r){
            ArrayList list = registredObjects.get(notificationName);
            if(list != null) {
                list.remove(r);
            }
        }
    
        public synchronized void postNotification(String notificationName){
            ArrayList list = registredObjects.get(notificationName);
            if(list != null) {
                for(Runnable r: list)
                    r.run();
            }
        }
    
    }
    

    and a usage for this will be:

      NotificationCenter.defaultCenter().addFucntionForNotification("buttonClick", new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MainActivity.this, "Hello There", Toast.LENGTH_LONG).show();
            }
        });
    

    tried to make the interface as similar to IOS as possible, but simpler (no object registration needed).

    hope that helps:)

提交回复
热议问题