Using Otto to update the listadapter from the GcmListenerService

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

}

+5
source share
1 answer

Yes, I get it. The answer here was not mysterious. In my singleton class, I created a Bus object and passed it as an instance. I did not do BusProvider. Therefore, when I called the message, it did not call the BusProvider overridden method, but the Bus method, which was not "thread safe" in my case. After I modified the code to reflect this recognition, it will work just fine!

+2
source

All Articles