The two days of a simple survey of Otto, found that the official website is very simple almost nothing, GitHub gave the sample is not very good. On-line technology blog Almost the same, I put my experience to write down, such as the fate of those who see the less detours.
We all know that this is a Publisher/subscriber model, also know that @produce use to register a need to announce the method, but I have never used in the actual application of @produce, just need to define an event, in need to publish the post of this event, Then @subscribe in the activity or fragment that needs to receive the message. It's three steps in detail.
The first step is to construct an event. The number of parameters that need to be passed is placed in the constructor method. Like what:
public class Textchangeevent {public final String s; Public Textchangeevent (String s) { THIS.S = s; } @Override public String toString () { return this.s; }
The second step is to post the post in the place where the message needs to be posted, which is an instance of the event. New one out is OK:
Findviewbyid (R.ID.BTN1). Setonclicklistener (New View.onclicklistener () { @Override public void OnClick (View V) { busprovider.getinstance (). Post (new Textchangeevent ("register")); AnotherActivity.this.finish (); } });
The third step, in the need to receive the message interface with @subscribe to receive a bit, you can:
@Subscribe public void OnTextChanged (Textchangeevent event) { Text.settext (event.tostring ()); LOG.V ("Cat", Event.tostring ()); }
It's over here. One from the news announcement. In the bus, and then to receive the place to be received processing process, there are a few points to note:
1, Otto recommends the use of a single case mode. If there is only one bus instance, then we construct a busprovider:
Import Com.squareup.otto.bus;public class Busprovider { private static final bus bus = new bus (); public static bus getinstance () { return bus; } Private Busprovider () { }}
2. The example given by Otto on GitHub is to register himself with the bus in an activity's Onresume () method, and cancel the registration in the OnPause () method, which I think is in practical use. An interface assumes no longer the foreground then it assumes that it also needs to receive messages then the method of canceling the register is placed in OnDestroy (), which prevents the register from being canceled when the interface enters the pause state:
@Override protected void OnDestroy () { Super.ondestroy (); Busprovider.getinstance (). Unregister (this); }
Well, Otto is easy to use bus mode. With the method of annotations can be completed the announcement and reception of the message, although performance than Eventbus, but the assumption that the code is concise, logical clear, then the loss of a bit of performance is acceptable, after all, the performance of today's CPU is nothing.
Android Otto Research