Communication between Android Services and Activities

前端 未结 4 1979

I want to develop an Android App with three activities and two services.

The first Service, named WebClientService, calls a REST API every

4条回答
  •  暖寄归人
    2020-12-16 06:37

    Use event bus for this communication. EventBus allows publish-subscribe-style communication between components without requiring the components to explicitly register with one another (and thus be aware of each other). It is designed exclusively to replace traditional Java in-process event distribution using explicit registration.

    There are a lot of them:

    http://square.github.io/otto/

    https://github.com/greenrobot/EventBus

    This is an example of Otto usage:

    Bus bus = new Bus();
    
    bus.post(new AnswerAvailableEvent(42));
    
    @Subscribe public void answerAvailable(AnswerAvailableEvent event) {
        // TODO: React to the event somehow!
    }
    
    bus.register(this); // In order to receive events, a class instance needs to register with the bus.
    

    To post from any thread (main or background), in you case a Service and receive events on the main thread:

    public class MainThreadBus extends Bus {
      private final Handler mHandler = new Handler(Looper.getMainLooper());
    
      @Override
      public void post(final Object event) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
          super.post(event);
        } else {
          mHandler.post(new Runnable() {
            @Override
            public void run() {
              MainThreadBus.super.post(event);
            }
          });
        }
      }
    

提交回复
热议问题