I use Otto to update my friends list when the other person debuts me. I have problems updating the user interface from the main thread, so I looked at it and "solved" the problem using this post . The code they use is as follows:
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); } }); } }
}
I am making a message as follows:
final Bus bus = BusProvider.getInstance(); Log.d(LOG_TAG, "Attempting to post from LBGcmListenerService!"); bus.post(new BuddiesEvent());
Essentially, when creating a Singleton Bus and passing through it, make sure that it is in the main stream. However, I cannot get this code to work. Instead, I created an instance of the handler in class I, as such:
final Bus bus = BusProvider.getInstance(); Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { bus.post(new BuddiesEvent()); } );
This works great. But I do not want to create a Handler object before each message . I don't know if this is a Java problem or a problem for Android, but I would appreciate it if someone could help me figure out how to get the singleton class to handle this problem. Thanks!
Fixed: Entering the correct code here:
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); } }); } }
}
source share