Android equivalent to NSNotificationCenter

前端 未结 8 2065
旧时难觅i
旧时难觅i 2020-12-22 15:35

In the process of porting an iPhone application over to android, I am looking for the best way to communicate within the app. Intents seem to be the way to go, is this the b

8条回答
  •  -上瘾入骨i
    2020-12-22 16:25

    I found that the usage of EventBus of Guava lib is the simplest way for publish-subscribe-style communication between components without requiring the components to explicitly register with one another

    see their sample on https://code.google.com/p/guava-libraries/wiki/EventBusExplained

    // Class is typically registered by the container.
    class EventBusChangeRecorder {
      @Subscribe public void recordCustomerChange(ChangeEvent e) {
        recordChange(e.getChange());
      }
    
    // somewhere during initialization
    eventBus.register(this);
    
    }
    
    // much later
    public void changeCustomer() {
      eventBus.post(new ChangeEvent("bla bla") );
    } 
    

    you can add this lib simply on Android Studio by adding a dependency to your build.gradle:

    compile 'com.google.guava:guava:17.0'
    

提交回复
热议问题