【发布时间】:2015-07-19 14:35:25
【问题描述】:
当好友取消我的好友时,我正在使用 Otto 刷新好友列表。我在从非主线程更新 UI 时遇到问题,因此我对其进行了调查并使用此 post“解决”了该问题。他们使用的代码是这样的:
public class BusProvider extends Bus{
public static final String LOG_TAG = BusProvider.class.getSimpleName();
private final Handler mainThread = new Handler(Looper.getMainLooper());
private static Bus mInstance;
public static synchronized Bus getInstance() {
if (mInstance == null) {
mInstance = new Bus();
}
return mInstance;
}
@Override
public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.d(LOG_TAG, "Posting event using super!");
super.post(event);
} else {
mainThread.post(new Runnable() {
@Override
public void run() {
Log.d(LOG_TAG, "Posting event using AndroidBus!");
BusProvider.super.post(event);
}
});
}
}
}
我是这样写的:
final Bus bus = BusProvider.getInstance();
Log.d(LOG_TAG, "Attempting to post from LBGcmListenerService!");
bus.post(new BuddiesEvent());
基本上是制作一个单例总线并通过它发布,确保它在主线程上。但是,我无法让该代码正常工作。相反,我在我发布的类中实例化了 Handler,如下所示:
final Bus bus = BusProvider.getInstance();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
bus.post(new BuddiesEvent());
}
);
这很好用。 但我不想在每篇文章之前都创建一个 Handler 对象。我不知道这是 Java 问题还是 Android 问题,但如果有人能帮我弄清楚如何让单例类处理这个问题,我将不胜感激。谢谢!
已修复:将正确的代码放在这里:
public class BusProvider extends Bus{
public static final String LOG_TAG = BusProvider.class.getSimpleName();
private final Handler mainThread = new Handler(Looper.getMainLooper());
private static BusProvider mInstance;
public static synchronized BusProvider getInstance() {
if (mInstance == null) {
mInstance = new BusProvider();
}
return mInstance;
}
@Override
public void post(final Object event) {
if (Looper.myLooper() == Looper.getMainLooper()) {
Log.d(LOG_TAG, "Posting event using super!");
super.post(event);
} else {
mainThread.post(new Runnable() {
@Override
public void run() {
Log.d(LOG_TAG, "Posting event using AndroidBus!");
BusProvider.super.post(event);
}
});
}
}
}
【问题讨论】:
-
AndroidBus类有什么问题? -
当我使用 AndroidBus 类并在我的 Bus 实例上调用 bus.post 时(上面的代码中没有显示 getInstance 方法),我收到一条错误消息,提示“访问了总线‘默认’来自非主线程 null"。当我在发布事件的类中实例化处理程序时,就像上面的第二段代码一样,一切正常。 @Gil,如果你能让 AndroidBus 类工作,从服务而不是活动发布,我很想看看如何!
-
代码看起来不错。我能想出的唯一可能的解释是线程的 looper 退出,所以当 Bus 发布时 Looper.myLooper() 返回 null (超类)。您能否检查一下 super.post(event) 或 AndroidBus.super.post(event) 中的哪一个失败了? (在通话前放置一些日志)
-
Ok Gil,我做了以下更改,但有趣的是都没有打印出来(参见上面的代码)。我想知道是否甚至调用了该帖子,或者是否在没有我修改的情况下调用了通用 Bus post 方法。当我命令单击发布帖子的类中的 post 方法时,它会将我路由到总线源代码,而不是我自己的类。你认为这可能是问题吗?如何强制它调用我的 post()?它是 BusProvider 的一个实例,所以它应该自动完成,不是吗?
标签: android multithreading post service otto