问题
I have implemented a service, where I handle the state changes(connect, disconnect, onServiceDiscoverd, onCharacteristicChange etc) and receiving data from another device through gatt Server.
My question is, Can the events be handled efficiently using Greenrobot Eventbus replacing broadcast receiver between service and Activity?
回答1:
Unlike LocalBroadcastManager, EventBus is more simple to use. You only go via 3 steps:
1- Create an event class. A simple Java class that represent the response when the action occur.
2- Register the event bus as a subscriber in your Activity onCreate method
EventBus.getDefault().register(this);
And of course, unregister it in your Activity onDestroy method
EventBus.getDefault().unregister(this);
3- The subscribing method is created in the same activity that registered for the EventBus. Example in WorkOrderActivity
@Subscribe
public void onEvent(EventClass event)
When the event occur, you should call the post method, passing the event object you created before.
EventBus.getDefault().post(new EventClass (Data));
As kmaini mentioned, you can replace it with LocalBroadcastManager, but you will have to map the data from the intent by yourself. Unlike EventBus which can pass objects.
Also, greenrobot, the creators of EventBus Library, answered this question here:
Q: How's EventBus different to Android's BroadcastReceiver/Intent system?
A: Unlike Android's BroadcastReceiver/Intent system, EventBus uses standard Java classes as events and offers a more convenient API. EventBus is intended for a lot more uses cases where you wouldn't want to go through the hassle of setting up Intents, preparing Intent extras, implementing broadcast receivers, and extracting Intent extras again. Also, EventBus comes with a much lower overhead.
回答2:
From another perspective, I believe broadcast managers in Android uses main thread handler's message queue to process events. So, if you are free to use a different thread (if you have no-UI events/jobs/tasks) with a proper queue (like using another HandlerThread) then you can take advantage of using that thread's specific queue to process your jobs, without interfering UI events and mixing your stuff with UI work. You can also play with the thread's priority value to balance the work.
Now, if GreenRobot provides that all functionality in a few lines of code, then I would definitely try it to see any performance gain.
回答3:
EventBus makes things much easier because you can pass is arbitrary Java objects along in the event.You not do the same with Intents
because your object has to implement Parcelable
and the "tedious" parcelable implementation which is something you might not what to do on an existing code base.
来源:https://stackoverflow.com/questions/33141091/is-it-good-to-replace-broadcast-receiver-with-greenrobot-eventbus-for-triggering