【EventBus】事件通信框架 ( 总结 | 手写事件通信框架完整代码示例 | 测试上述框架 )

举报
韩曙亮 发表于 2022/01/14 00:03:15 2022/01/14
【摘要】 文章目录 一、消息中心二、订阅方法时的注解三、订阅方法封装四、订阅对象-方法封装五、线程模式六、Activity 中测试上述框架七、博客源码 一、消息中心 该消息中...





一、消息中心



该消息中心是事件通信框架的核心代码 , 负责订阅方法的注册 , 消息事件转发 , 订阅方法取消注册操作 ;

package com.eventbus_demo.myeventbus;

import android.os.Handler;
import android.os.Looper;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyEventBus {

    /**
     * 方法缓存
     *      Key - 订阅类类型
     *      Value - 订阅方法 MySubscriberMethod 的集合
     * 取名与 EventBus 一致
     */
    private static final Map<Class<?>, List<MySubscriberMethod>> METHOD_CACHE = new HashMap<>();

    /**
     * 解除注册时使用
     *      Key - 订阅者对象
     *      Value - 订阅者对象中所有的订阅方法的事件参数类型集合
     *
     * 根据该订阅者对象 , 查找所有订阅方法的事件参数类型 ,  然后再到  METHOD_CACHE 中 ,
     *      根据事件参数类型 , 查找对应的 MySubscriberMethod 集合
     *      MySubscriberMethod 中封装 订阅者对象 + 订阅方法
     *
     */
    private final Map<Object, List<Class<?>>> typesBySubscriber;

    /**
     * Key - 订阅者方法事件参数类型
     * Value - 封装 订阅者对象 与 订阅方法 的 MySubscription 集合
     * 在构造函数中初始化
     * CopyOnWriteArrayList 在写入数据时会拷贝一个副本 ,
     *      写完之后 , 将引用指向新的副本 ,
     *      该集合的线程安全级别很高
     */
    private final Map<Class<?>, CopyOnWriteArrayList<MySubscription>> subscriptionsByEventType;

    /**
     * 线程池
     */
    private final ExecutorService executorService;

    /**
     * 全局单例
     */
    private static MyEventBus instance;
    private MyEventBus() {
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        executorService = Executors.newCachedThreadPool();
    }
    public static MyEventBus getInstance() {
        if (instance == null) {
            instance = new MyEventBus();
        }
        return instance;
    }

    /**
     * 注册订阅者
     * @param subscriber
     */
    public void register(Object subscriber) {
        // 获取订阅者所属类
        Class<?> clazz = subscriber.getClass();
        // 查找订阅方法
        List<MySubscriberMethod> subscriberMethods = findSubscriberMethods(clazz);

        // 遍历所有订阅方法 , 进行订阅
        //      首先确保查找到的订阅方法不为空 , 并且个数大于等于 1 个
        if (subscriberMethods != null && !subscriberMethods.isEmpty()) {
            for (MySubscriberMethod method : subscriberMethods) {
                // 正式进行订阅
                subscribe(subscriber, method);
            }
        }
    }

    /**
     * 方法订阅
     *      将 订阅方法参数类型 和 订阅类 + 订阅方法 封装类 , 保存到
     *      Map<Class<?>, CopyOnWriteArrayList<MySubscription>> subscriptionsByEventType 集合中
     *          Key - 订阅者方法事件参数类型
     *          Value - 封装 订阅者对象 与 订阅方法 的 MySubscription 集合
     *
     * 取消注册数据准备
     *      取消注册数据存放在 Map<Object, List<Class<?>>> typesBySubscriber 集合中
     *          Key - 订阅者对象
     *          Value - 订阅者方法参数集合
     *
     * @param subscriber    订阅者对象
     * @param subscriberMethod        订阅方法
     */
    private void subscribe(Object subscriber, MySubscriberMethod subscriberMethod) {
        // 获取订阅方法接收的参数类型
        Class<?> eventType = subscriberMethod.getEventType();
        // 获取 eventType 参数类型对应的 订阅者封装类 ( 封装 订阅者对象 + 订阅方法 ) 集合
        CopyOnWriteArrayList<MySubscription> subscriptions =
                subscriptionsByEventType.get(eventType);

        // 如果获取的集合为空 , 说明 eventType 参数对应的订阅方法一个也没有注册过
        //      这里先创建一个集合 , 放到 subscriptionsByEventType 键值对中
        if (subscriptions == null) {
            // 创建集合
            subscriptions = new CopyOnWriteArrayList<>();
            // 将集合设置到 subscriptionsByEventType 键值对集合中
            subscriptionsByEventType.put(eventType, subscriptions);
        }

        // 封装 订阅者对象 + 订阅方法 对象
        MySubscription subscription = new MySubscription(subscriber, subscriberMethod);
        // 将创建的 订阅者对象 + 订阅方法 对象 添加到  CopyOnWriteArrayList 集合中
        subscriptions.add(subscription);

        // 为取消注册准备数据
        //      设置 Map<Object, List<Class<?>>> typesBySubscriber
        List<Class<?>> eventTypes = typesBySubscriber.get(subscriber);
        if (eventTypes == null) {
            // 创建新的集合, 用于存放订阅方法的参数类型
            eventTypes = new ArrayList<>();
            // 将新的集合设置到 Map<Object, List<Class<?>>> typesBySubscriber 集合中
            typesBySubscriber.put(subscriber, eventTypes);
        }
        // 将新的 订阅方法类型 放入到集合中
        eventTypes.add(eventType);
    }

    /**
     * 根据订阅方法的事件参数查找订阅方法
     * @param subscriberClass   订阅者对象的类型
     * @return
     */
    private List<MySubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        // 获取 Class<?> clazz 参数类型对应的 订阅者封装类
        List<MySubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);

        // 此处后期重构, 减少缩进

        if (subscriberMethods == null) {
            // 说明是首次获取 , 初始化 METHOD_CACHE 缓存
            // 反射获取 Class<?> subscriberClass 中的所有订阅方法
            subscriberMethods = findByReflection(subscriberClass);

            if (! subscriberMethods.isEmpty()) {
                METHOD_CACHE.put(subscriberClass, subscriberMethods);
            }
        } else {
            // 如果当前不是第一次获取, 则直接返回从 METHOD_CACHE 缓存中获取的 订阅者封装类 集合
            return subscriberMethods;
        }

        // 该分支走不到
        return subscriberMethods;
    }

    /**
     * 通过反射获取 Class<?> subscriberClass 订阅方法
     * @param subscriberClass 订阅类
     * @return
     */
    private List<MySubscriberMethod> findByReflection(Class<?> subscriberClass) {
        // 要返回的 MySubscriberMethod 集合
        List<MySubscriberMethod> subscriberMethods = new ArrayList<>();

        // 通过反射获取所有带 @MySubscribe 注解的方法
        Method[] methods = subscriberClass.getMethods();

        // 遍历所有的方法 , 查找注解
        for (Method method : methods) {
            // 获取方法修饰符
            int modifiers = method.getModifiers();
            // 获取方法参数
            Class<?>[] params = method.getParameterTypes();
            // 确保修饰符必须是 public , 参数长度必须是 1
            if (modifiers == Modifier.PUBLIC && params.length == 1) {
                // 获取 MySubscribe 注解
                MySubscribe annotation = method.getAnnotation(MySubscribe.class);
                // 获取注解不为空
                if (annotation != null) {
                    // 获取线程模式
                    MyThreadMode threadMode = annotation.threadMode();
                    // 此时已经完全确定该方法是一个订阅方法 , 直接进行封装
                    MySubscriberMethod subscriberMethod = new MySubscriberMethod(
                            method,         // 方法对象
                            threadMode,     // 线程模式
                            params[0]       // 事件参数
                    );
                    // 加入到返回集合中
                    subscriberMethods.add(subscriberMethod);
                }
            }
        }
        return subscriberMethods;
    }

    /**
     * 接收到了 发布者 Publisher 发送给本消息中心 的 Event 消息事件对象
     *      将该事件对象转发给相应接收该类型消息的 订阅者 ( 订阅对象 + 订阅方法 )
     *      通过事件类型到
     *      Map<Class<?>, CopyOnWriteArrayList<MySubscription>> subscriptionsByEventType
     *      集合中查找相应的 订阅对象 + 订阅方法
     * @param event
     */
    public void post(Object event) {
        // 获取事件类型
        Class<?> eventType = event.getClass();
        // 获取事件类型对应的 订阅者 集合
        CopyOnWriteArrayList<MySubscription> subscriptions =
                subscriptionsByEventType.get(eventType);

        // 确保订阅者大于等于 1 个
        if (subscriptions != null && subscriptions.size() > 0) {
            // 遍历订阅者并调用订阅方法
            for (MySubscription subscription : subscriptions) {
                postSingleSubscription(subscription, event);
            }
        }
    }

    /**
     * 调用订阅方法
     * @param subscription
     * @param event
     */
    private void postSingleSubscription(MySubscription subscription, Object event) {
        // 判断当前线程是否是主线程
        //      获取 mainLooper 与 myLooper 进行比较 , 如果一致 , 说明该线程是主线程
        boolean isMainThread = false;
        // 下面的情况下 , 线程是主线程
        if (Looper.getMainLooper() == Looper.myLooper()) {
            isMainThread = true;
        }

        // 判断订阅方法的线程模式
        MyThreadMode threadMode = subscription.getSubscriberMethod().getThreadMode();

        switch (threadMode) {
            case POSTING:
                // 直接在发布线程调用订阅方法
                invokeMethod(subscription, event);
                break;
            case MAIN:
            case MAIN_ORDERED:
                // 如果发布线程是主线程, 直接调用
                if (isMainThread) {
                    invokeMethod(subscription, event);
                } else {
                    // 将订阅方法放到主线程执行
                    // 获取主线程 Looper , 并通过 Looper 创建 Handler
                    Handler handler = new Handler(Looper.getMainLooper());
                    // 在主线程中执行订阅方法
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            invokeMethod(subscription, event);
                        }
                    });
                }
                break;
            case BACKGROUND:
            case ASYNC:
                // 如果是主线程 , 切换到子线程执行
                if (isMainThread) {
                    // 在线程池中执行方法
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            invokeMethod(subscription, event);
                        }
                    });
                } else {
                    // 如果是子线程直接执行
                    invokeMethod(subscription, event);
                }
                break;
        }
    }

    /**
     * 调用订阅者的订阅方法
     * @param subscription 订阅者对象 + 订阅方法
     * @param event 发布者传递的消息事件
     */
    private void invokeMethod(MySubscription subscription, Object event) {
        try {
            // 通过反射调用订阅方法
            subscription.getSubscriberMethod().getMethod().invoke(
                    subscription.getSubscriber(),   // 订阅者对象
                    event                           // 事件参数类型
            );
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消注册
     *      从 Map<Object, List<Class<?>>> typesBySubscriber 集合中获取
     *      订阅者对象 中的 订阅方法 参数集合
     *
     *      然后再到
     *      Map<Class<?>, CopyOnWriteArrayList<MySubscription>> subscriptionsByEventType
     *      集合中获取 订阅方法参数类型 对应的 CopyOnWriteArrayList<MySubscription>> 集合
     *      MySubscription 中封装了 订阅者对象 + 订阅方法
     * @param subscriber
     */
    public void unregister(Object subscriber) {
        // 首先获取 订阅者 对象中的订阅方法的参数集合
        List<Class<?>> types = typesBySubscriber.get(subscriber);

        // 遍历参数类型
        for (Class<?> type: types) {
            // 获取 接收 type 事件类型的 订阅者集合
            //      MySubscription 中封装了订阅者对象 + 订阅方法
            CopyOnWriteArrayList<MySubscription> subscriptions =
                    subscriptionsByEventType.get(type);

            // 判定 CopyOnWriteArrayList<MySubscription> 集合中的 MySubscription 元素
            //      如果如果 封装类对象 中的 订阅者对象 与 本次取消注册的订阅者对象相同 , 则从集合中移除该订阅者

            // 记录集合大小
            int subscriptionsSize = subscriptions.size();
            for (int i = 0; i < subscriptionsSize; i++) {
                // 获取 订阅者对象 + 订阅方法 封装类 对象
                MySubscription subscription = subscriptions.get(i);

                // 如果 封装类对象 中的 订阅者对象 与 本次取消注册的订阅者对象相同
                //      将其从该集合中删除
                if (subscription.getSubscriber() == subscriber) {
                    // 删除 i 索引元素
                    subscriptions.remove(i);
                    // 应用新的集合大小 , 集合少了一个元素
                    subscriptionsSize--;
                    // 第 i 个元素被删除了 , 之后会自增遍历下一个元素
                    //      下一次遍历的还是第 i 个元素
                    //      由于后面循环操作需要自增 , 想要之后仍然遍历第 i 个元素 ,
                    //      这里对 i 进行自减操作
                    i--;

                }
            }
            // 删除了订阅者 , 就完成了取消注册操作
        }
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 355
  • 356
  • 357
  • 358




二、订阅方法时的注解



定义一个注解 , 该注解用于修饰方法 ElementType.METHOD , 在运行时 , 用户调用 register 注册订阅者时 , 会分析哪个方法中存在该注解 , 将有注解的方法保存起来 , 以便之后的调用 ;

该注解需要保存到运行时 RetentionPolicy.RUNTIME ;

package com.eventbus_demo.myeventbus;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)     // 该注解保留到运行时
@Target(ElementType.METHOD)             // 该注解作用于方法
public @interface MySubscribe {
    /**
     * 注解属性, 设置线程模式, 默认是 POSTING,
     *      即在发布线程调用订阅方法
     * @return
     */
    MyThreadMode threadMode() default MyThreadMode.POSTING;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17




三、订阅方法封装



将 订阅方法 , 订阅方法的线程模式 , 订阅方法接收的事件类型 , 封装到类中 ;

package com.eventbus_demo.myeventbus;

import java.lang.reflect.Method;

/**
 * 该类中用于保存订阅方法相关信息
 */
public class MySubscriberMethod {
    /**
     * 订阅方法
     */
    private final Method method;
    /**
     * 订阅方法的线程模式
     */
    private final MyThreadMode threadMode;
    /**
     * 订阅方法接收的事件类型
     */
    private final Class<?> eventType;

    public MySubscriberMethod(Method method, MyThreadMode threadMode, Class<?> eventType) {
        this.method = method;
        this.threadMode = threadMode;
        this.eventType = eventType;
    }

    public Method getMethod() {
        return method;
    }

    public MyThreadMode getThreadMode() {
        return threadMode;
    }

    public Class<?> getEventType() {
        return eventType;
    }
}


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40




四、订阅对象-方法封装



再次进行封装 , 将 订阅者对象 和 订阅方法 , 封装到一个类中 , 这个类对象是 注册 , 取消注册 , 事件调用 操作的基本单元 ;

获取到该类的对象 , 就可以执行订阅方法 ;

package com.eventbus_demo.myeventbus;

/**
 * 封装 订阅者对象 与 订阅方法
 */
public class MySubscription {
    /**
     * 订阅者对象
     */
    private final Object subscriber;
    /**
     * 订阅方法
     */
    private final MySubscriberMethod subscriberMethod;

    public MySubscription(Object subscriber, MySubscriberMethod subscriberMethod) {
        this.subscriber = subscriber;
        this.subscriberMethod = subscriberMethod;
    }

    public Object getSubscriber() {
        return subscriber;
    }

    public MySubscriberMethod getSubscriberMethod() {
        return subscriberMethod;
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28




五、线程模式



仿照 EventBus 的线程模式 , 直接照搬过来 ;

线程模式用法参考 【EventBus】Subscribe 注解分析 ( Subscribe 注解属性 | threadMode 线程模型 | POSTING | MAIN | MAIN_ORDERED | ASYNC) ;

package com.eventbus_demo.myeventbus;

/**
 * 直接使用 EventBus 中的现成模式
 */
public enum MyThreadMode {
    POSTING,
    MAIN,
    MAIN_ORDERED,
    BACKGROUND,
    ASYNC
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12




六、Activity 中测试上述框架



在 Activity 中使用 @MySubscribe 注解修饰处理消息的方法 , 该方法必须是 public void 修饰的 , 只有一个参数 , 参数类型随意 , 调用 MyEventBus.getInstance().post 方法即可发送消息到该方法进行处理 ;

    /**
     * 使用 @MySubscribe 注解修饰处理消息的方法
     *      该方法必须是 public void 修饰的
     *      只有一个参数 , 参数类型随意
     *      调用 MyEventBus.getInstance().post 即可发送消息到该方法进行处理
     * @param msg
     */
    @MySubscribe
    public void onMessgeEvent(String msg){
        textView.setText(msg);
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

onCreate 方法中 , 注册订阅方法 ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 首先注册订阅 EventBus
        MyEventBus.getInstance().register(this);
    }

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

点击按钮 , 发送消息事件 , 这里发送了一个字符串 ;

        textView = findViewById(R.id.textView);
        // 设置点击事件, 点击后发送消息
        textView.setOnClickListener((View view)->{
            MyEventBus.getInstance().post("Hello EventBus !");
        });

  
 
  • 1
  • 2
  • 3
  • 4
  • 5

完整 Activity 代码 :

package com.eventbus_demo;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.eventbus_demo.myeventbus.MyEventBus;
import com.eventbus_demo.myeventbus.MySubscribe;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 使用 MyEventBus 依赖库
 */
public class MainActivity3 extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);
        // 设置点击事件, 点击后发送消息
        textView.setOnClickListener((View view)->{
            MyEventBus.getInstance().post("Hello EventBus !");
        });

        // 首先注册订阅 EventBus
        MyEventBus.getInstance().register(this);
    }

    /**
     * 使用 @Subscribe 注解修饰处理消息的方法
     *      该方法必须是 public void 修饰的
     *      只有一个参数 , 参数类型随意
     *      调用 EventBus.getDefault().post 即可发送消息到该方法进行处理
     * @param msg
     */
    @MySubscribe
    public void onMessgeEvent(String msg){
        textView.setText(msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 取消注册
        MyEventBus.getInstance().unregister(this);
    }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

执行效果 : 点击后 , 页面变为如下效果 ;

在这里插入图片描述





七、博客源码



GitHub : https://github.com/han1202012/EventBus_Demo

文章来源: hanshuliang.blog.csdn.net,作者:韩曙亮,版权归原作者所有,如需转载,请联系作者。

原文链接:hanshuliang.blog.csdn.net/article/details/120552981

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200