How to send event from Service to Activity with Otto event bus?

后端 未结 7 1750
心在旅途
心在旅途 2020-12-02 05:19

Simple BusProvider.getInstance().post() bring exception not main thread. How to send event from Service to Activity with Otto event bus?

7条回答
  •  失恋的感觉
    2020-12-02 06:07

    To post from any thread (main or background) and receive on the main thread, try something like

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

    Note: credit goes to Jake Wharton and "pommedeterresaute" at https://github.com/square/otto/issues/38 for the general approach. I just implemented it with a wrapper class rather than a subclass.

提交回复
热议问题