dc2471f451ffdab8793578a793a8b280a9d6d481.svn-base 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package eVVM.apk.other;
  2. import android.support.v4.util.ArrayMap;
  3. import org.greenrobot.eventbus.EventBus;
  4. import org.greenrobot.eventbus.Subscribe;
  5. import org.greenrobot.eventbus.ThreadMode;
  6. import org.greenrobot.eventbus.meta.SubscriberInfoIndex;
  7. import eVVM.apk.MyEventBusIndex;
  8. /**
  9. * desc : EventBus 管理类
  10. */
  11. public final class EventBusManager {
  12. // EventBus 索引类
  13. private static final SubscriberInfoIndex SUBSCRIBE_INDEX = new MyEventBusIndex();
  14. // 这个类是否需要注册 EventBus
  15. private static final ArrayMap<String, Boolean> SUBSCRIBE_EVENT = new ArrayMap<>();
  16. // 不允许被外部实例化
  17. private EventBusManager() {}
  18. /**
  19. * 初始化 EventBus
  20. */
  21. public static void init() {
  22. EventBus.builder()
  23. .ignoreGeneratedIndex(false) // 使用 Apt 插件
  24. .addIndex(SUBSCRIBE_INDEX) // 添加索引类
  25. .installDefaultEventBus(); // 作为默认配置
  26. }
  27. /**
  28. * 注册 EventBus
  29. */
  30. public static void register(Object subscriber) {
  31. if (canSubscribeEvent(subscriber)) {
  32. EventBus.getDefault().register(subscriber);
  33. }
  34. }
  35. /**
  36. * 反注册 EventBus
  37. */
  38. public static void unregister(Object subscriber) {
  39. if (canSubscribeEvent(subscriber) && EventBus.getDefault().isRegistered(subscriber)) {
  40. EventBus.getDefault().unregister(subscriber);
  41. }
  42. }
  43. /**
  44. * 判断是否使用了 EventBus 注解
  45. *
  46. * @param subscriber 被订阅的类
  47. */
  48. private static boolean canSubscribeEvent(Object subscriber) {
  49. Class<?> clazz = subscriber.getClass();
  50. // 这个 Class 类型有没有遍历过
  51. Boolean result = SUBSCRIBE_EVENT.get(clazz.getName());
  52. if (result != null) {
  53. // 有的话直接返回结果
  54. return result;
  55. }
  56. // 没有的话进行遍历
  57. while (clazz != null) {
  58. // 如果索引集合中有这个 Class 类型的订阅信息,则这个类型的对象都需要注册 EventBus
  59. if (SUBSCRIBE_INDEX.getSubscriberInfo(clazz) != null) {
  60. // 这个类需要注册 EventBus
  61. result = true;
  62. clazz = null;
  63. } else {
  64. String clazzName = clazz.getName();
  65. // 跳过系统类(忽略 java. javax. android. androidx. 等开头包名的类)
  66. if (clazzName.startsWith("java") || clazzName.startsWith("android")) {
  67. clazz = null;
  68. } else {
  69. // 往上查找
  70. clazz = clazz.getSuperclass();
  71. }
  72. }
  73. }
  74. // 这个类不需要注册 EventBus
  75. if (result == null) {
  76. result = false;
  77. }
  78. SUBSCRIBE_EVENT.put(subscriber.getClass().getName(), result);
  79. return result;
  80. }
  81. @Subscribe(threadMode = ThreadMode.MAIN)
  82. public void onEventBus(EventBusManager helper) {
  83. // 占位,只为了能生成 MyEventBusIndex 索引类
  84. // 如果项目中已经有用到 @Subscribe 去注解方法,这个方法可以直接删除
  85. }
  86. }