1.SubScribe注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Subscrible {
ThreadMode threadMode() default ThreadMode.MAIN;
}
2.SubScribeMethod封装
public class SubScribeMethod {
/**
* 方法
*/
private Method method;
/**
* 线程模式
*/
private ThreadMode threadMode;
/**
* 参数
*/
private Class<?> type;
public SubScribeMethod() {
}
public SubScribeMethod(Method method, ThreadMode threadMode, Class<?> type) {
this.method = method;
this.threadMode = threadMode;
this.type = type;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public ThreadMode getThreadMode() {
return threadMode;
}
public void setThreadMode(ThreadMode threadMode) {
this.threadMode = threadMode;
}
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
}
线程模式
public enum ThreadMode {
MAIN,
BACKGROUND
}
EvenBus单例实现:regiseter unRegister,post
public class EventBus {
private ConcurrentHashMap<Object, List<SubScribeMethod>> mCache;
private static EventBus instance;
private Handler mHandler;
private ThreadPoolExecutor mThreadPoolExecutor;
public static EventBus getDefault() {
if (instance == null) {
synchronized (EventBus.class) {
if (instance == null) {
instance = new EventBus();
}
}
}
return instance;
}
public EventBus() {
this.mCache = new ConcurrentHashMap<>(16);
mHandler = new Handler(Looper.getMainLooper());
mThreadPoolExecutor = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, new PriorityBlockingQueue<Runnable>());
}
/**
* 注册
* @param object
*/
public void register(Object object) {
if (object == null) {
return;
}
// 从缓存中拿
List<SubScribeMethod> list = mCache.get(object);
if (list == null) {
list = findSubScribeInfos(object);
mCache.put(object, list);
}
}
private List<SubScribeMethod> findSubScribeInfos(Object object) {
List<SubScribeMethod> subScribeMethods = new ArrayList<>();
Class<?> clazz = object.getClass();
while (clazz != null) {
if (clazz.getName().startsWith("java.") || clazz.getName().startsWith("javax.")
|| clazz.getName().startsWith("android.")) {
break;
}
// 获取当前所有的方法
Method[] methods = clazz.getMethods();
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
Class<?>[] types = method.getParameterTypes();
if (types.length == 1) {
Subscrible subscribe = method.getAnnotation(Subscrible.class);
// 当前注解
if (subscribe != null) {
// 当前线程模式
ThreadMode threadMode = subscribe.threadMode();
SubScribeMethod subScribeMethod = new SubScribeMethod();
subScribeMethod.setType(types[0]);
subScribeMethod.setThreadMode(threadMode);
subScribeMethod.setMethod(method);
subScribeMethods.add(subScribeMethod);
}
}
}
}
clazz = clazz.getSuperclass();
}
return subScribeMethods;
}
/**
* 取消注册
* @param object
*/
public void unRegister(Object object) {
// 去除当前的注册缓存
mCache.remove(object);
}
/**
* post方法
* @param object
*/
public void post(final Object object) {
// 循环遍历map
Set<Object> set = mCache.keySet();
Iterator<Object> iterable = set.iterator();
while (iterable.hasNext()) {
final Object key = iterable.next();
List<SubScribeMethod> methodLis = mCache.get(key);
Class<?> clazz = object.getClass();
if (methodLis != null && !methodLis.isEmpty()) {
for (final SubScribeMethod subScribeMethod : methodLis) {
// 参数的type一样
if (subScribeMethod.getType().isAssignableFrom(clazz)) {
// 区分线程进行
if (subScribeMethod.getThreadMode() == ThreadMode.MAIN) {
if (isMainUI()) {
involke(subScribeMethod, key, object);
} else {
mHandler.post(new Runnable() {
@Override
public void run() {
involke(subScribeMethod, key, object);
}
});
}
} else if (subScribeMethod.getThreadMode() == ThreadMode.BACKGROUND) {
if (isMainUI()) {
mThreadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
involke(subScribeMethod, key, object);
}
});
} else {
involke(subScribeMethod, key, object);
}
}
}
}
}
}
}
private void involke(SubScribeMethod subScribeMethod, Object object, Object type) {
Method method = subScribeMethod.getMethod();
if (method != null) {
try {
method.invoke(object, type);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
private boolean isMainUI() {
return Looper.getMainLooper() == Looper.myLooper();
}
}
例子:MainActivity 接收消息
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
findViewById(R.id.b).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unRegister(this);
}
@Subscrible(threadMode = ThreadMode.MAIN)
public void getMainMessage(EventBean eventBean){
Log.d("zpb","Main from="+ eventBean.getFrom()+":: to="+eventBean.getTo()+" thread="+Thread.currentThread().getName());
}
@Subscrible(threadMode = ThreadMode.BACKGROUND)
public void getThreadMessage(EventBean eventBean){
Log.d("zpb"," thread from="+ eventBean.getFrom()+":: to="+eventBean.getTo()+" thread="+Thread.currentThread().getName());
}
@Subscrible
public void getStringMessage(String message){
Log.d("zpb","string value ="+message);
}
}
SecondActivity发送消息
public class SecondActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secord_activity);
findViewById(R.id.b1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBean eventBean = new EventBean();
eventBean.setFrom("b1 main thread");
eventBean.setTo("main actityv");
EventBus.getDefault().post(eventBean);
}
});
findViewById(R.id.b2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
EventBean eventBean = new EventBean();
eventBean.setFrom("b2 subThread");
eventBean.setTo("mainactivity");
EventBus.getDefault().post(eventBean);
}
}).start();
}
});
findViewById(R.id.b3).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post("发送子付出啊");
}
});
}
}