/**
* 手写需要在方法上添加该参数,让该方法执行的时候,在哪个线程接收通知
*/
public enum ThreadMode {
/**
* 当前线程接收
*/
PostThread,
/**
* 主线程接收
*/
MainThread,
/**
* 异步线程接收
*/
BackgroundThread,
/**
* 独立线程接收
*/
Async,
}
/**
*订阅的事件和方法.
* 1:处理事件线程。ThreadMode
* 2:处理事件订阅方法类
* 3:Method 处理事件方法名称
*
* 该类存储的是 一个方法 对应注解上的参数 和类名称
*/
public class SubscribleMethod {
private final Method method;
private final ThreadMode threadMode;
private final Class<?> aClassType;
public SubscribleMethod(Method method, ThreadMode threadMode, Class<?> aClassType) {
this.method = method;
this.threadMode = threadMode;
this.aClassType = aClassType;
}
public Method getMethod() {
return method;
}
public ThreadMode getThreadMode() {
return threadMode;
}
public Class<?> getaClassType() {
return aClassType;
}
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Subscribe {
ThreadMode threadMode() default ThreadMode.PostThread;
}
package com.ml.demo06.eventbus;
import android.os.Handler;
import android.os.Looper;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class EventBus {
private final Handler handler;
private final ExecutorService executorService;
private final HashMap<Object, List<SubscribleMethod>> cacheMap;
public static class EventBusHolder {
private static EventBus instance = new EventBus();
}
private EventBus() {
//主线程中的handler
handler = new Handler(Looper.getMainLooper());
executorService = Executors.newCachedThreadPool();
cacheMap = new HashMap<>();
}
/**
* eventbus的注册
*/
public void register(Object activity) {
//根据activity对象获取该对象所有事件列表
List<SubscribleMethod> list = cacheMap.get(activity);
if (list == null) {
//创建list关于activity 的事件
list = getSubscribleMethods(activity);
cacheMap.put(activity, list);
}
}
/**
* 发送事件
*
* @param friend
*/
public void post(final Object friend) {
//遍历查找到的subscribe 方法 ,获取map中的所有key
Set<Object> set = cacheMap.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
final Object value = iterator.next();
List<SubscribleMethod> list = cacheMap.get(value);
//获取一个activity中对应的所有注解方法
for (final SubscribleMethod subscribleMethod : list) {
ThreadMode threadMode = subscribleMethod.getThreadMode();
switch (threadMode) {
case MainThread: //主线程调用
if (Looper.myLooper() == Looper.getMainLooper()) {
invoke(subscribleMethod, value, friend);
} else {
handler.post(new Runnable() {
@Override
public void run() {
invoke(subscribleMethod, value, friend);
}
});
}
break;
case Async: //异步线程
if (Looper.myLooper() == Looper.getMainLooper()) {
//执行在主线程,切换线程
executorService.execute(new Runnable() {
@Override
public void run() {
invoke(subscribleMethod, value, friend);
}
});
} else {
//执行在子线程
invoke(subscribleMethod, value, friend);
}
break;
default:
break;
}
}
}
}
//执行注解方法
private void invoke(SubscribleMethod subscribleMethod, Object value, Object friend) {
Method method = subscribleMethod.getMethod();
try {
method.invoke(value, friend);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 反射得到Subscrible处理事件的方法
* 将activty所有方法上有注解的方法收集起来,包括方法名对应的注解参数
*
* @param activity
* @return
*/
private List<SubscribleMethod> getSubscribleMethods(Object activity) {
List<SubscribleMethod> list = new ArrayList<>();
Class<?> classType = activity.getClass();
while (classType != null) {
String className = classType.getName();
if (className.startsWith("java.") || className.startsWith("javax.")
|| className.startsWith("android.")) {
break;
}
//符合要求 类或接口声明的所有方法
Method[] methods = classType.getDeclaredMethods();
for (Method method : methods) {
//获取方法上有 @Subscribe 注解的方法
Subscribe subscribe = method.getAnnotation(Subscribe.class);
if (subscribe == null) {
continue;
}
//监测这个方法符不符合 获取方法的参数
Class<?>[] paramtypes = method.getParameterTypes();
if (paramtypes.length != 1) {
throw new RuntimeException("只能有一个参数");
}
//获取注解上的参数
ThreadMode threadMode = subscribe.threadMode();
SubscribleMethod subscribleMethod = new SubscribleMethod(method, threadMode, paramtypes[0]);
list.add(subscribleMethod);
}
classType = classType.getSuperclass();
}
return list;
}
/**
* EventBus注销
*
* @param activity
*/
public void unregister(Object activity) {
List<SubscribleMethod> list = cacheMap.get(activity);
if (list != null) {
cacheMap.remove(activity);
}
}
}
版权声明:本文为BunnyCoffer原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。