Thanks for the glamour of open source. Open source is beautiful.
- Subscribermethodfinder Discovery Registration Method Class
- Subscribermethod method combination for user registration
- Subscription class for user and method key values
- Asyncposter Asynchronous Initiator Class
- Handlerposter Main Thread Initiator class
- Postbeen Message Class (initiator class executes callbacks based on message)
- Eventbus Access Class (Builder mode)
**
Attention!!!!! Opening a new thread within the OnCreate method generally defaults to the main thread, which can only be initiated when the main thread is idle. Looper.myqueue (). Addidlehandler
**
Mainactivity
PackageCom.lvshujun.customeventbus;ImportCom.lvshujun.event.EventBus;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Looper;ImportAndroid.os.MessageQueue.IdleHandler; Public class mainactivity extends Activity { @Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Eventbus.getdefault (). Register ( This);//eventbus.getdefault (). Unregister (this);Looper.myqueue (). Addidlehandler (NewIdlehandler () {@Override Public Boolean Queueidle() {//TODO auto-generated method stubEventbus.getdefault (). Post (NewResponseevent ());return false; } }); } Public void Oneventmainthread(Responseevent event) {System.out.println (Thread.CurrentThread (). GetName ()); }}
Subscribermethodfinder
PackageCom.lvshujun.event;ImportJava.lang.reflect.Method;ImportJava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.List;ImportJava.util.Map; Public class subscribermethodfinder { Private Static Finalmap<string, list<subscribermethod>> Methodcache =NewHashmap<string, list<subscribermethod>> (); List<subscribermethod> findsubscribermethods (class<?> subscriberclass) {String cName = SubscriberClass . GetName (); List<subscribermethod> Subscribermethods =NULL;synchronized(Methodcache) {subscribermethods = Methodcache.get (cName); }if(Subscribermethods! =NULL)returnSubscribermethods; Subscribermethods =NewArraylist<subscribermethod> ();if(Subscriberclass! =NULL) {method[] methods = Subscriberclass.getdeclaredmethods (); for(Method method:methods) {String methodName = Method.getname ();if(Methodname.startswith ("OnEvent") {class<?>[] parametertypes = Method.getparametertypes ();if(Parametertypes.length = =1) {Subscribermethod SM =NewSubscribermethod (method, parametertypes[0]); Subscribermethods.add (SM); }}}} methodcache.put (CName, subscribermethods);returnSubscribermethods; }}
Subscription
package com.lvshujun.event;publicfinalclass Subscription { publicfinal Object subscriber; publicfinal SubscriberMethod subscriberMethod; Subscription(Object subscriber, SubscriberMethod subscriberMethod) { this.subscriber = subscriber; this.subscriberMethod = subscriberMethod; }}
Subscribermethod
package com.lvshujun.event;import java.lang.reflect.Method;publicfinalclass SubscriberMethod { finalpublic Method method; finalpublic Class<?> eventType; SubscriberMethod(Method method, Class<?> eventType) { this.method = method; this.eventType = eventType; }}
Handlerposter
PackageCom.lvshujun.event;ImportJava.util.LinkedList;ImportJava.util.Queue;ImportAndroid.os.Handler;ImportAndroid.os.Looper;ImportAndroid.os.Message;Final class handlerposter extends Handler { PrivateQueue<postbeen> queue;Private FinalEventbus Eventbus; Handlerposter (Eventbus Eventbus, Looper Looper) {Super(Looper); This. Eventbus = Eventbus; Queue =NewLinkedlist<postbeen> (); }@Overridepublic void Handlemessage (Message msg) {Try{Postbeen pendingpost = Queue.poll ();if(Pendingpost = =NULL) { }Else{Eventbus.invokesubscriber (pendingpost); } }Catch(Exception e) { }finally{}} void Enqueue (Subscription Subscription, Object event) {Queue.add (NewPostbeen (event, subscription)); SendMessage (Obtainmessage ()); }}
Asyncposter
PackageCom.lvshujun.event;ImportJava.util.LinkedList;ImportJava.util.Queue; Public class asyncposter implements Runnable { PrivateQueue<postbeen> queue;PrivateEventbus Eventbus; Public Asyncposter(Eventbus Eventbus) {//Super (Looper); This. Eventbus = Eventbus; Queue =NewLinkedlist<postbeen> (); }@Override Public void Run() {//TODO auto-generated method stub Try{Postbeen pendingpost = Queue.poll ();if(Pendingpost = =NULL) { }Else{Eventbus.invokesubscriber (pendingpost); } }Catch(Exception e) { }finally{ } }voidEnqueue (Subscription Subscription, Object event) {Queue.add (NewPostbeen (event, subscription)); EventBus.executorService.execute ( This); }}
Postbeen
package com.lvshujun.event;publicclass PostBeen { publicevent; public Subscription subscription; publicPostBeen(Object obj,Subscription sub) { this.event = obj; this.subscription = sub; }}
Eventbus
PackageCom.lvshujun.event;ImportJava.lang.reflect.InvocationTargetException;ImportJava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.List;ImportJava.util.Map;ImportJava.util.concurrent.CopyOnWriteArrayList;ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors;ImportAndroid.os.Looper; Public class eventbus { PrivateSubscribermethodfinder MethodFinder; Executorservice Executorservice = Executors.newcachedthreadpool ();PrivateHandlerposter Handlerposter;PrivateAsyncposter Asyncposter;Private FinalMap<class<?>, copyonwritearraylist<subscription>> Subscriptionsbyeventtype;Private FinalMap<object, list<class<?>>> Typesbysubscriber; Public StaticEventbus single; Public StaticEventbusGetdefault() {if(single =NULL) {synchronized(Eventbus.class) {if(single =NULL) {single =NewEventbus (); } } }returnSingle } Public synchronized void Register(Object subscriber) {list<subscribermethod> subscribermethods = Methodfinder.findsubscribermethods (Subscriber.getClass ()); for(Subscribermethod method:subscribermethods) {class<?> EventType = Method.eventtype; copyonwritearraylist<subscription> subscriptions = Subscriptionsbyeventtype.get (EventType); Subscription newsubscription =NewSubscription (subscriber, method);if(Subscriptions = =NULL) {subscriptions =NewCopyonwritearraylist<subscription> (); Subscriptionsbyeventtype.put (EventType, subscriptions); } subscriptions.add (Newsubscription); list<class<?>> subscribedevents = typesbysubscriber.get (subscriber);if(Subscribedevents = =NULL) {subscribedevents =NewArraylist<class<?>> (); Typesbysubscriber.put (subscriber, subscribedevents); } subscribedevents.add (EventType); } } Public synchronized void Unregister(Object subscriber) {list<class<?>> subscribedtypes = typesbysubscriber.get (subscriber);if(Subscribedtypes! =NULL) { for(class<?> eventtype:subscribedtypes) {List<subscription> subscriptions = Subscriptionsbyeventtype.get (EventType);if(Subscriptions! =NULL) {intSize = Subscriptions.size (); for(inti =0; i < size; i++) {Subscription Subscription = Subscriptions.get (i);if(Subscription.subscriber = = subscriber) {System.out.println (Subscription.subscriberMethod.method.getName ()); Subscriptions.remove (i); i--; size--; }}}} typesbysubscriber.remove (subscriber); } } Public Eventbus() {MethodFinder =NewSubscribermethodfinder (); Subscriptionsbyeventtype =NewHashmap<class<?>, copyonwritearraylist<subscription>> (); Typesbysubscriber =NewHashmap<object, list<class<?>>> (); Handlerposter =NewHandlerposter ( This, Looper.getmainlooper ()); Asyncposter =NewAsyncposter ( This); } Public void Post(Object obj) {List<subscription> subscriptions = Subscriptionsbyeventtype.get (Obj.getclass ());if(Subscriptions! =NULL) { for(Subscription subscription:subscriptions) {System.out.println (Subscription.subscriberMethod.method.getName ());//handlerposter.enqueue (subscription, obj);Asyncposter.enqueue (subscription, obj); } } } Public void Invokesubscriber(Postbeen been)throwsIllegalArgumentException, Illegalaccessexception, invocationtargetexception {Subscription sub = been.subscription; Sub.subscriberMethod.method.invoke (Sub.subscriber, been.event); }}
http://download.csdn.net/detail/q22232222/9063671
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Eventbus Open source Framework (imitation)