• EventBus 3.0使用相关


    一 引入方法

      可以去github的官网中下载EventBus的相关资源  地址:https://github.com/greenrobot/EventBus

      当然还有他的官方网站 http://greenrobot.org/eventbus/

     Eclipse用户需要下载其jar包;AndroidStudio用户 可以在 build.gradle直接添加引用

    compile 'org.greenrobot:eventbus:3.0.0'

     

    二  使用

     1:在监听者的Activity或者Fragment或者其他地方注册及解除事件的绑定

        主要是通过使用EventBus,使Fragment之间的通信可以写的非常简洁易懂

      @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            /**创建界面时订阅事件,接收消息*/
            EventBus.getDefault().register(this);
        }
    
     @Override
        public void onDestroy() {
            super.onDestroy();
            /**界面销毁时,取消订阅*/
            EventBus.getDefault().unregister(this);
        }
    

      因为EventBus使用的是单例模式,所以可以实现一句话实现注册和取消注册;也可以通过Builder来自己创建;

         以上完成后就相当于注册了本界面接受消息,这样你在其他地方发消息时就可以通知本界面(是比Handler好用)

    2:写传送Message POJO(Plain Ordinary Java Object)简单的Java对象

    public class MsgEvent1 {
        private String msg;
    
        public MsgEvent1(String msg) {
            super();
            this.msg = msg;
        }
        public String getMsg() {
            return msg;
        }
    }

    2:写监听方法

    这个监听方法名字你可以自己取,但是得写上@Subscribe 注解,且形参必须要和传送过来的参数类型一致;

    那么既然名字能随意去取,怎么能控制运行的线程呢,答案就是在注解中控制 @Subscribe(threadMode = ThreadMode.MAIN)

    需要设置ThreadMode即可

      @Subscribe
            public void onEvent(MsgEvent1 msg){
                String content = msg.getMsg()
                        + "
     ThreadName: " + Thread.currentThread().getName()
                        + "
     ThreadId: " + Thread.currentThread().getId();
                System.out.println("onEvent(MsgEvent1 msg)收到" + content);
                tv.setText(content);
            }

    3:在任何地方发送消息

    且只需要一句话就行

    EventBus.getDefault().post(new MsgEvent1("Fuck World!!));
    这样EventBus使用就完成了

    有几个注意的地方
    1:哪个监听者会作出相应这要看你post的类型!!
    2:监听方法注意加@Subscribe注释,否则会报错:
    Caused by: org.greenrobot.eventbus.EventBusException: Subscriber class com.example.XXXXXX and its super classes have no public methods with the @Subscribe annotation
    3:监听方法为Public方法
  • 相关阅读:
    让8个数码管全部显示数字
    程序存储空间与内存
    点亮数码管,显示具体的数字
    为什么点亮小灯时,有时是输入数字0,有时是数字1
    循环点亮LED灯
    keil 编程时,总是中英文切换时,格式混乱。
    点亮LED灯
    学生管理系统(C 大一期末作业)
    ivew ui
    git常见操作
  • 原文地址:https://www.cnblogs.com/fengfenghuifei/p/6277835.html
Copyright © 2020-2023  润新知