Bra*_*don 5 service post multithreading android otto
当伙伴们对我进行研究时,我正在使用Otto来刷新好友列表.我在从非主线程更新UI时遇到问题,所以我查看了它并使用这篇文章 "解决"了这个问题.他们使用的代码是这样的:
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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
}
我发这样的帖子:
final Bus bus = BusProvider.getInstance();
Log.d(LOG_TAG, "Attempting to post from LBGcmListenerService!");
bus.post(new BuddiesEvent());
Run Code Online (Sandbox Code Playgroud)
基本上制作单身总线并通过它发布,确保它在主线程上.但是,我无法使用该代码.我改为在我发布的类中实例化Handler,如下:
final Bus bus = BusProvider.getInstance();
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
bus.post(new BuddiesEvent());
}
);
Run Code Online (Sandbox Code Playgroud)
这非常有效.但是我不希望在每个帖子之前都要创建一个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);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
}
是的,我明白了。这里的答案并不神秘。在我的单例类中,我创建了一个 Bus 对象并将其作为实例移交。我并没有创建 BusProvider。因此,当我调用 post 时,它不是调用 BusProvider 重写方法,而是调用 Bus 方法,在我的情况下,该方法不是“线程安全”的。在我更改代码以反映这种识别之后,效果非常好!
| 归档时间: |
|
| 查看次数: |
410 次 |
| 最近记录: |