Androideventbus, I didn't hear you.
Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/40794879, this article from: "Zhang Hongyang Blog" 1, overview
Recently, everyone interviewed said that often asked Eventbus,github on a decisive down, address: Https://github.com/greenrobot/EventBus, is indeed a good framework, mainly for the release and subscription of events.
Eventbus definition: is a publish/Subscribe event bus.
That should contain 4 ingredients: Publisher, subscriber, event, bus.
So what is the relationship between the four of them?
It is obvious that subscribers subscribe to events to the bus and the sender publishes events.
The general should be such a relationship:
Subscribers can subscribe to multiple events, and the sender can post any event, and the publisher can also be a subscriber.
Well, after a general understanding of the basic relationship, we use case-driven to teach you how to do it;
2, the code is the best teacher
I believe that everyone has some understanding of fragment, now our demand is such, two fragment composition of the main interface, the left fragment is a directory, that is, the list, the fragment on the right is the details panel;
A, the list of directories is obtained from the network.
b, the dynamic Update Details panel when clicking on an entry in the directory;
:
In view of this demand, our traditional approach is:
A, directory fragment in the OnCreate to open the thread to access the network to obtain data, get finished, through handler to update the interface.
b, in the directory of the fragment to provide an interface, and then the details panel to register the interface, when a click, go back to this interface, let the details panel changes.
Actually this kind of practice also is good, but after having eventbus, what kind of change does our interaction take place? Let's wait and see.
First of all, please mention:
Eventbus.getdefault (). Register (this);//Subscribe to Events
Eventbus.getdefault (). Post (object);//Publish Event
Eventbus.getdefault (). Unregister (this);//Unsubscribe
1. Mainactivity and its layout
Package Com.angeldevil.eventbusdemo;import Android.os.bundle;import android.support.v4.app.FragmentActivity; public class Mainactivity extends fragmentactivity{@Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main);}}
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " android:baselinealigned= "false" android:divider= "Android:attr/dividerhorizontal" android:o rientation= "Horizontal" android:showdividers= "middle" > <fragment android:id= "@+id/item_list" android:name= "com.angeldevil.eventbusdemo.ItemListFragment" android:layout_width= "0dip" Android : layout_height= "match_parent" android:layout_weight= "1"/> <fragment android:id= "@+id/item _detail_container " android:name=" com.angeldevil.eventbusdemo.ItemDetailFragment " android:layout_ Width= "0dip" android:layout_height= "match_parent" android:layout_weight= "2"/></linearlayout >
Can see, we mainactvity can say no line of code, layout file is composed of two fragment;
2, Itemlistfragment
First look at an entity class:
Package Com.angeldevil.eventbusdemo;import Java.util.arraylist;import Java.util.list;public class Item{public String Id;public String content;public static list<item> ITEMS = new arraylist<item> (); static{//Add 6 Sample ITEMS.A Dditem (New Item ("1", "Item 1")), AddItem (New Item ("2", "Item 2"), AddItem (New Item ("3", "Item 3")), AddItem (New Item ("4", " Item 4 ")), AddItem (New Item (" 5 "," Item 5 "), AddItem (" 6 "," Item 6 ")); private static void AddItem (item item) {Items.Add (item);} Public Item (string ID, string content) {this.id = Id;this.content = content;} @Overridepublic String toString () {return content;}}
Package Com.angeldevil.eventbusdemo;import Android.os.bundle;import Android.support.v4.app.listfragment;import Android.view.view;import Android.widget.arrayadapter;import Android.widget.listview;import Com.angeldevil.eventbusdemo.event.itemlistevent;import De.greenrobot.event.eventbus;public class ItemListFragment Extends listfragment{@Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); /Registereventbus.getdefault (). Register (this);} @Overridepublic void OnDestroy () {Super.ondestroy ();//Unregistereventbus.getdefault (). Unregister (this);} @Overridepublic void onviewcreated (view view, Bundle savedinstancestate) {super.onviewcreated (view, savedinstancestate)///Open line loads load list new thread () {public void run () {try{thread.sleep (2000);//analog delay//publish event, Cheng event Eventbus.getdefault (). Post (new Itemlistevent (Item.items)) in the background line; catch (Interruptedexception e) {e.printstacktrace ();}};}. Start ();} public void Oneventmainthread (Itemlistevent event) {Setlistadapter (new ARRAYADAPTER<item> (Getactivity (), Android. R.layout.simple_list_item_activated_1,android. R.id.text1, Event.getitems ()));} @Overridepublic void Onlistitemclick (ListView listview, View view, int Position,long id) {Super.onlistitemclick ( ListView, view, position, id); Eventbus.getdefault (). Post (Getlistview (). Getitematposition (position));}}
Itemlistfragment inside the OnCreate inside the event of the subscription, OnDestroy inside the event cancellation; onviewcreated We simulated a sub-thread to the network to load the data, after the success we call
The Eventbus.getdefault (). Post (new Itemlistevent (Item.items)); an event was released;
Onlistitemclick is the Click event of the ListView, we call the Eventbus.getdefault (). Post (Getlistview (). Getitematposition (position)); To publish an event,
Getlistview (). Getitematposition (position) is of type item type;
Careful you must have found some strange things, the direct new Thread () to obtain the data, unexpectedly did not use handler; Our interface has changed, then when the list is bound data?
Take a closer look at the code and find this method:
public void Oneventmainthread (Itemlistevent event)
{
Setlistadapter (New arrayadapter<item> (Getactivity (),
Android. R.layout.simple_list_item_activated_1,
Android. R.id.text1, Event.getitems ()));
}
It should be the data that this method binds to the list. So how is this method being called?
Now it's time to subscribe to events and publish events:
If the method name begins with OnEvent, it means subscribing to an event, mainthread meaning, and the method is eventually executed on the UI thread, which is executed when the event is published.
So when will the event be released?
Our Oneventmainthread trigger time should be after the new thread () execution completes, you can see that the child thread execution completes, the Eventbus.getdefault (). Post (New Itemlistevent ( Item.items));
means that an event is released, and when the event is published, our oneventmainthread is executed, so what is the correlation between the two?
In fact and the type of the parameter, we oneventmainthread need to receive a itemlistevent, we also released a itemlistevent instance.
Now we have a complete rationale:
Execute eventbus.getdefault (). Register (this) in OnCreate, meaning to let Eventbus scan the current class and record all the methods of onevent at the beginning. Using Map,key as the parameter type for the method, the value contains our method.
This way, after the execution of the OnCreate, our oneventmainthread is stored in the Eventbus as a key-value pair.
Then when the child thread finishes executing, calling Eventbus.getdefault (). Post (new Itemlistevent (Item.items)), Eventbus will go to map to find the method based on the type of arguments in the post. So we found our oneventmainthread and finally called the reflection to execute our method.
Now it's time to understand that the whole process is running, and then the callback without the interface can be explained.
Now we're looking at the code when item clicks on the Eventbus.getdefault (). Post (Getlistview (). Getitematposition (position)); We also released an event with the parameter item This event is for the fragment of detailed information to update the data, needless to say, according to the above speculation, the details of the fragment inside one has sucha method: public void Oneventmainthread (item item ), isn't it? Let's go and see.
3, Itemdetailfragment
Package Com.angeldevil.eventbusdemo;import Android.os.bundle;import Android.support.v4.app.fragment;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.TextView ; Import De.greenrobot.event.eventbus;public class Itemdetailfragment extends Fragment{private TextView tvdetail;@ overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);// Registereventbus.getdefault (). Register (this);} @Overridepublic void OnDestroy () {Super.ondestroy ();//Unregistereventbus.getdefault (). Unregister (this);} /** list will send some events when clicked, receive event update details */public void Oneventmainthread (item item) {if (item! = NULL) Tvdetail.settext (item.content );} @Overridepublic View Oncreateview (Layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {view Rootview = Inflater.inflate (R.layout.fragment_item_detail,container, false); Tvdetail = (TextView) Rootview.findviewbyid (R.id.item_detail); return rootview;}}
As expected, there is really a way to Oneventmainthread (item item). Of course, you must first write the Eventbus.getdefault (). Register (this) in oncreate; let Eventbus scan again.
So this fragment process is: OnCreate, Eventbus scan the current class, the oneventmainthread is stored as key-value pairs, the key is Item.class, the value is the object containing the method.
Then when item in Itemlistfragment is clicked, an event is released: Eventbus.getdefault (). Post (Getlistview (). Getitematposition (position)); The type of the argument happens to be item, so it triggers our
Oneventmainthread the method and passes the item argument in, we update the control.
4. Event
Here's another event class:
Package Com.angeldevil.eventbusdemo;import Java.util.list;public class event{/** list Load event */public static class Itemlistevent{private list<item> items;public itemlistevent (list<item> items) {this.items = items;} Public list<item> GetItems () {return items;}}}
Itemlistevent we use in the Itemlistfragment, as is the parameter in the Oneventmainthread. Why encapsulate such a class? will be explained in the Eventbus source parsing later.
The initial usage of our eventbus is complete. Throughout the code, wood has handler, Wood has asyntask, Wood has an interface callback; But, we like the magic to achieve our needs; to tell me, what is coupling, didn't see ~ ~ ~
3, Eventbus's Threadmode
Eventbus consists of 4 Threadmode:postthread,mainthread,backgroundthread,async
Mainthread we are no strangers; we have used them.
The specific usage, extremely simple, the method name is: Oneventpostthread, Oneventmainthread,oneventbackgroundthread,oneventasync can
What's the difference?
Oneventmainthread represents this method in the UI thread execution
Oneventpostthread represents this method that executes on the thread that is currently publishing the event
Backgroundthread This method, if the event is published in a non-UI thread, it is executed directly, and published in the same thread. If the event is published on the UI thread, join the background task queue and use the thread pool one after another.
Async joins the background task queue and calls with the thread pool, noting that there is no backgroundthread one by one.
4. Off-Topic
You can use Eventbus to try the following:
When a broadcast is received, such as a text message, it is displayed on the interface.
Open a service, start a timed thread in the server, and constantly update Activityui.
Wait a minute... After that, you will find the charm of Eventbus!
Statement: The above two fragment example is I down on the internet, made a simple change, although very simple, but it is very good to explain the problem. Look at the package name should be Angeldevil written, here to express thanks.
By the way, an official give an example of what performance contrasts, then a bunch of testcase, not intuitive.
If you want to understand eventbus in depth, see: Android Eventbus Source parsing takes you in-depth understanding of Eventbus, I believe you can relieve a lot of confusion, understand the design of the framework of the United States.
SOURCE Click to download
I built a QQ group, convenient for everyone to communicate. Group number:55032675
----------------------------------------------------------------------------------------------------------
Bo Master part of the video has been online, if you do not like boring text, please poke (first record, look forward to your support):
1, High imitation 5.2.1 main interface and message alert
2, high imitation QQ5.0 slide
3. android Robot "Little Mu" implementation
4.Android Custom controls create Android streaming layouts and popular tags
Original link This article by Bean John Blog Backup expert remote One click release
Androideventbus The actual combat did not hear you on the Out (reprint)