Android framework to teach you how to write inter-component communication framework Eventbus

Source: Internet
Author: User

Reprint please indicate the source:http://blog.csdn.net/lmj623565791/article/details/41096639, this article is from: "Zhang Hongyang's Blog"1. Overview

About Eventbus's introduction, there have been two articles: Android Eventbus not heard you on the out and Android Eventbus source code parsing take you in-depth understanding Eventbus, if you think there are problems, it's okay, Next I will take you to create a framework from scratch to write such a frame ~ ~ ~

First we look back, this thing is in register, scanning class in the compound naming specification method, save to a map, and then Post, find the matching method, reflection call; Well, then according to this sentence, we begin to write the framework tour ~ ~ ~

2, is still the original formula

The following example code and Android Eventbus have not heard you on the out of the Basic agreement, so I posted part

1, Itemlistfragment

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 Com.zhy.eventbus.eventbus;public class ItemListFragment Extends listfragment{@Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); /Registereventbus.getinstatnce (). Register (this);} @Overridepublic void OnDestroy () {Super.ondestroy ();//Unregistereventbus.getinstatnce (). 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.getinstatnce (). Post (new Itemlistevent (Item.items)) in the background line; catch (Interruptedexception e) {e.printstacktrace ();}};}. Start ();} public void Oneventui (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.getinstatnce (). Post (Getlistview (). Getitematposition (position));}}
2, 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 Com.zhy.eventbus.eventbus;public class Itemdetailfragment extends Fragment{private TextView tvdetail;@ overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);// Registereventbus.getinstatnce (). Register (this);} @Overridepublic void OnDestroy () {Super.ondestroy ();//Unregistereventbus.getinstatnce (). Unregister (this);} /** list will send some events when clicked, receive event update details */public void Oneventui (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 you can see, we used the itemlistfragment inside:

Eventbus.getinstatnce (). Post (new Itemlistevent (Item.items)); To publish an event and update our list;

When you click on item, use Eventbus.getinstatnce (). Post (Getlistview (). Getitematposition (position)); an event was released, Updated the list of our itemdetailfragment;

Effect:


The same as the previous touch ~ ~ ~

But note that now we are using eventbus.getinstatnce (), Concurrency is Eventbus.getdefault (), and look under the package name import Com.zhy.eventbus.EventBus;

I think you should understand, this is our own class to achieve the realization of ~ ~ ~

All right, let's get this class together.

PS: The above code and, is completely for the integrity of the blog, do not be offended ~ ~

3, out of nothing 1, getinstance

We are here for convenience, simply and rudely using the Han mode to create a singleton:

private static Eventbus Eventbus = new Eventbus ();p ublic static Eventbus getinstatnce () {return eventbus;} Private Eventbus () {Mhandler = new Handler (Looper.getmainlooper ());}

Then a mhandler is initialized in the constructor, yes, it is used to invoke methods in the UI thread.

Next Look at register

2. Register

/* * Our powerful MAP, store our method */private static Map<class, copyonwritearraylist<subscribemethod>> Msubscribemethodsbyeventtype = new Hashmap<class, copyonwritearraylist<subscribemethod>> ();p ublic void Register (Object subscriber) {Class clazz = Subscriber.getclass (); Method[] methods = Clazz.getdeclaredmethods (); copyonwritearraylist<subscribemethod> subscribemethods = null;/** * Traverse all Methods */for (method Method:methods) {String m Ethodname = Method.getname ();/** * Determines whether the method starts with OnEvent */if (Methodname.startswith ("OnEvent")) {Subscribemethod Subscribemethod = null;//method hit in advance on what thread to run. The default is in the UI thread string threadmode = Methodname.substring ("onEvent". Length ()); Threadmode mode = Threadmode.ui; class<?>[] parametertypes = Method.getparametertypes ();//The number of parameters is 1if (parametertypes.length = = 1) {class<?> EventType = parametertypes[0];synchronized (this) {if (Msubscribemethodsbyeventtype.containskey (EventType)) { Subscribemethods = Msubscribemethodsbyeventtype.get (EventType);} Else{subscribEmethods = new copyonwritearraylist<subscribemethod> (); Msubscribemethodsbyeventtype.put (EventType, subscribemethods);}} if (Threadmode.equals ("Async")) {mode = Threadmode.async;} Extract the Method,mode, the method of the Class object, the type of the stored number is encapsulated as Subscribemethodsubscribemethod = new Subscribemethod (method, Mode,subscriber); Subscribemethods.add (Subscribemethod);}}} Enum Threadmode{ui, Async}class Subscribemethod{method Method; Threadmode threadmode;object subscriber;public Subscribemethod (method, Threadmode threadmode,object subscriber {This.method = Method;this.threadmode = Threadmode;this.subscriber = subscriber;}}


You can see that we used a map to store all the methods, and the key is the type of the parameter class;value to copyonwritearraylist<subscribemethod>

Here we encapsulate a subscribemethod, which stores all the parameters of the method we need to run, after all we run, we need the method, the object where the method resides, and the thread on which to run; three objects are enough, of course, to be indispensable

Register inside, we traverse all methods of this class, find onevent beginning, encapsulate into subscribemethod, exist map inside, of course, a parameter type corresponds many methods, so value is a copyonwritearraylist.

When the scan is complete, we have finished storing the method.

Also, we are doing this by default in the UI thread, and if the method is Oneventasync it is assumed to execute on the child thread, we only support both modes, simplifying a little ~

3. Post

private static threadlocal<postingthread> Mpostingthread = new threadlocal<postingthread> () {@ Overridepublic Postingthread Get () {return new Postingthread ();}}; public void post (object eventtypeinstance) {//Gets the Postingthread object in the thread postingthread Postingthread = Mpostingthread.get ( );p Ostingthread.ismainthread = looper.getmainlooper () = = Looper.mylooper ();//Add events to the event queue list<object> EventQueue = Postingthread.meventqueue;eventqueue.add (eventtypeinstance);//prevents multiple calls to if (postingthread.isposting) {return;} Postingthread.isposting = true;//takes out all events to invoke while (!eventqueue.isempty ()) {Object EventType = eventqueue.remove (0); Postevent (EventType, postingthread);} Postingthread.isposting = false;}

We learned the source code here, and also engaged in a variable in the current thread, storing an event queue and the state of the event;

Class postingthread{list<object> Meventqueue = new Arraylist<object> (); Boolean Ismainthread;boolean isposting;}

The resulting event is first added to the event queue and then taken out to invoke postevent

private void Postevent (final Object eventtype, Postingthread postingthread) {Copyonwritearraylist<subscribemethod > subscribemethods = null;synchronized (this) {subscribemethods = Msubscribemethodsbyeventtype.get ( Eventtype.getclass ());} For (final Subscribemethod subscribemethod:subscribemethods) {if (Subscribemethod.threadmode = = Threadmode.ui) {if ( Postingthread.ismainthread) {InvokeMethod (EventType, Subscribemethod);} else{mhandler.post (New Runnable () {@ overridepublic void Run () {InvokeMethod (EventType, Subscribemethod);});}} Else{new asynctask<void, Void, void> () {@Overrideprotected void Doinbackground (void ... params) {InvokeMethod ( EventType, subscribemethod); return null;}};}}

Postevent is also very simple, directly according to the parameter type, go to map to the method, according to its threadmode, if the UI thread, then judge the current thread, if it is the UI thread, call directly, otherwise through handler execution;

If the non-UI thread, here we directly open a thread to execute;

InvokeMethod is very simple, is the reflection call method ~

private void InvokeMethod (Object eventtype, Subscribemethod subscribemethod) {Try{subscribemethod.method.invoke ( Subscribemethod.subscriber, EventType);} catch (Exception e) {e.printstacktrace ();}}

4, unregister

public void Unregister (Object subscriber) {Class clazz = Subscriber.getclass (); Method[] methods = Clazz.getdeclaredmethods (); list<subscribemethod> subscribemethods = null;for (Method method:methods) {String methodName = Method.getname (); if (Methodname.startswith ("OnEvent")) {class<?>[] parametertypes = Method.getparametertypes (); Parametertypes.length = = 1) {synchronized (this) {msubscribemethodsbyeventtype.remove (parametertypes);}}}}

Unregister, because we did not save any of the auxiliary state, we can only go through the method ~ ~ But through this, can also reflect the eventbus inside several map of the role of ~ ~

Also, we do not support some state queries, or because we do not have some auxiliary states, such as Isregister and so on.

To this, our Eventbus wrote well, more than 100 lines of code, certainly no Eventbus robust, the main purpose is to learn the thoughts of others, after their own writing such a class, I believe that the understanding of Eventbus more profound ~ interview, I would like to take a pen to the interviewer to see, haha ~~

5. Eventbus Best Practices

The previous article, many friends asked, if I have multiple method parameters are the same, it is not post one this parameter, will be more than one method call, and at this time I want to invoke the specified method what to do?

Also, there will be many places in the project to receive the List parameter, and the list<t> in the generic is inconsistent, so may also post (List), will call many methods, resulting in an error.

Indeed, the above-mentioned, non-treatment will certainly arise;

However, it is recommended that when using Eventbus, create an event class that encapsulates each of your parameters (or possibly conflicting arguments) into a class:

For example:

public class Event{public Static class Userlistevent{public list<user> users;} public static class Itemlistevent{public list<item> items;}}

In this case, there will be no call conflict.



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





Android framework to teach you how to write inter-component communication framework Eventbus

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.