Android framework to teach you how to write the 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

Introduction to Eventbus. There are two previous: Android Eventbus actual combat did not hear you on the out and Android Eventbus source code parsing takes you in-depth understanding eventbus. If you think there is a problem, it doesn't matter, then I will take you hand in hand to build this framework from scratch ~ ~ ~

First of all, let's recall that this thing is the way to scan a composite naming convention in a class when it is in register, to save to a map, and then Post. Find a matching method that reflects the call; well, then according to this sentence. We started to write the framework tour ~ ~ ~

2, is still the original formula

The following example code and Android Eventbus do not know that you are out of the basic Agreement. So I'm just going to put a 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 thread load list new thread () {public void run () {try{thread.sleep (2000);//analog delay//advertisement 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;}}

Can see. We used it in the itemlistfragment:

Eventbus.getinstatnce (). Post (new Itemlistevent (Item.items)); to announce an event. Then we updated our list;

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

Effect:


The same as the previous touch ~ ~ ~

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

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

All right, let's get this class together.

PS: The above code and. All for the integrity of the blog. No Offense ~ ~

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 methods */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 Method */for (method Method:methods) {String m Ethodname = Method.getname ();/** * Infer whether the method starts with OnEvent */if (Methodname.startswith ("OnEvent")) {Subscribemethod Subscribemethod = null;//method hit in advance on what thread to execute. The default is in the UI thread string threadmode = Methodname.substring ("onEvent". Length ()); Threadmode mode = Threadmode.ui; class<?

>[] parametertypes = Method.getparametertypes ();//The number of references 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;} Extracts the Method,mode, the class object where the method resides. The type of the save 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;}}



Can see that we have used a map to store all the methods. Key is the type of the parameter class;value is copyonwritearraylist<subscribemethod>

Here we encapsulate a subscribemethod, which stores all the parameters of the method we need to execute, after all we do. The method on which the method is located is required. And on what thread to execute; three objects are sufficient. Of course, also indispensable ~ ~

In register, we traverse all methods of the class, find the beginning of onevent, and encapsulate it into subscribemethod. There is a map inside. Of course, there is a very many method for a parameter type, so value is a copyonwritearraylist.

The scan is complete. We're finished. Stores the method.

Another point, we are here by default in the UI thread execution, assuming that the method is oneventasync feel in the child thread execution, we also only support the two modes, simplify 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 ();//Increase 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've learned the source code here, and we've got a variable in the current thread that stores an event queue and the state of the event;

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

The events that are finally announced are added to the event queue first. And then take it out and call 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 easy, directly based on the type of parameters, to map to the method, according to its threadmode. Assume the UI thread. The current thread is inferred. The assumption is that the UI thread is called directly. otherwise executed through handler;

Assume a non-UI thread. Here we directly open a thread to execute;

InvokeMethod is very easy. 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[0]);}}}}

When unregister. Since we do not have the auxiliary state of whatever, we can only go through the method again ~ ~ just through this. can also reflect the role of several maps inside the Eventbus ~ ~

And. We also do not support some state queries, or because we do not save some auxiliary state, such as Isregister and so on.

By this, our Eventbus has been written. More than 100 lines of code. Certainly no eventbus strong, 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 just a pen to the interviewer to see, haha ~ ~

5. Eventbus Best Practices

Before the article, very many friends asked. Suppose I have the same number of methods, would it not be a post one that will be called by multiple methods, and at this point I want to invoke the specified method?

And also. There are very many places in the project to receive list parameters, and generics in list<t> are inconsistent, so it is possible to post (list). Very many methods are called. Cause an error.

Do. Above, the non-treatment will certainly appear;

However, it is recommended that you use Eventbus. Create an event class that encapsulates each of your parameters (or potentially conflicting parameters) into a class:

Like what:

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

Such words. There's nothing going on. Call Conflict ~ ~



Source code 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, assuming you do not like boring text. Please poke (first record). Looking forward to your support):

1, High imitation 5.2.1 main interface and message alert

2, high imitation QQ5.0 sideways slip

3. android Robot "Little Mu" implementation





Android framework to teach you how to write the 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.