如何从服务发送事件到活动与奥托事件总线? [英] How to send event from Service to Activity with Otto event bus?

查看:92
本文介绍了如何从服务发送事件到活动与奥托事件总线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单 BusProvider.getInstance()后()带来的异常没有主线程。 如何从服务发送事件到活动与奥托事件总线?

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

推荐答案

从任何线程(主要还是背景)发布和接收的主线程,尝试像

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

注:归功于杰克沃顿商学院和pommedeterresaute在 https://github.com/square/otto/issues / 38 的一般方法。我只是实现它的包装类,而不是一个子类。

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.

这篇关于如何从服务发送事件到活动与奥托事件总线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆