Android EventBus使用(不含源码解析)

本文涉及的产品
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
云解析 DNS,旗舰版 1个月
全局流量管理 GTM,标准版 1个月
简介: 官方文档:https://github.com/greenrobot/EventBussimplifies the communication between componentsdecouples event senders and receiv...

官方文档:https://github.com/greenrobot/EventBus

simplifies the communication between components
decouples event senders and receivers
performs well with Activities, Fragments, and background threads
avoids complex and error-prone dependencies and life cycle issues
makes your code simpler
is fast
is tiny (~50k jar)
is proven in practice by apps with 100,000,000+ installs
has advanced features like delivery threads, subscriber priorities, etc.
这句话大概是说:
简化组件之间的通信
解耦事件发送者和接收者
对活动、片段和后台线程进行良好的操作
而且非常快
jar包小至50k
已经有超过了一亿用户安装
而且还可以定义优先级


不看了,反正对于开发者来说就一句话:好用!

不废话了,下面开始说使用教程:
1、加入EventBus3.0依赖

implementation 'org.greenrobot:eventbus:3.0.0'

2、既然说了EventBus是用来传值用的,那么先定义这个值吧。
创建一个实体类,MyStudent

public class MyStudent extends Observable {

    private String name;
    private int sex;
    private int old;

    public String getName() {
        return name == null ? "" : name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public int getOld() {
        return old;
    }

    public void setOld(int old) {
        this.old = old;
    }

    @Override
    public String toString() {
        return "MyStudent{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", old=" + old +
                '}';
    }

3、值有了,那么这个值有入口和出口的吧
建立两个Activity,我这里就建两个,一个MainActivity,一个Main2Activity,(这里创建流程就不写了,只写Activity中的核心代码)

public class MainActivity extends AppCompatActivity {
    private Button button;
    private MyStudent myStudent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);//注册eventbus
        button = findViewById(R.id.main_btn);

        button .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, Main2Activity.class));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(MainActivity.this);
    }
//接收事件,EventBus3.0之后采用注解的方式
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MyStudent myStudent) {
        Log.e("MainActivity", myStudent.toString());
    }
}

下面看看Main2

public class Main2Activity extends AppCompatActivity {
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        button = findViewById(R.id.main2_btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyStudent myStudent = new MyStudent();
                myStudent.setName("eventbus");
                myStudent.setOld(2);
                myStudent.setSex(2);
                EventBus.getDefault().post(myStudent);
               finish();
            }
        });
    }

这里Log的打印结果是:(我不说,打印结果希望看博客的同学可以自己动手操作一波,这样你的记忆力才深刻。)

4、其实最基本的使用到这里就完了,有一些需要注意的地方在这里说一下:
我们可以看到,在接收参数的方法上面会有一个注解:

 @Subscribe(threadMode = ThreadMode.MAIN) 

在接收参数的方法上一定要带这个注解,不然参数会接收不到。
注解中的:
threadMode = ThreadMode.MAIN,指的是在什么线程下操作。我们点进去源码看看

public enum ThreadMode {
    /**
     * Subscriber will be called in the same thread, which is posting the event. This is the default. Event delivery
     * implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for
     * simple tasks that are known to complete is a very short time without requiring the main thread. Event handlers
     * using this mode must return quickly to avoid blocking the posting thread, which may be the main thread.
     */
    POSTING,

    /**
     * Subscriber will be called in Android's main thread (sometimes referred to as UI thread). If the posting thread is
     * the main thread, event handler methods will be called directly. Event handlers using this mode must return
     * quickly to avoid blocking the main thread.
     */
    MAIN,

    /**
     * Subscriber will be called in a background thread. If posting thread is not the main thread, event handler methods
     * will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single
     * background thread, that will deliver all its events sequentially. Event handlers using this mode should try to
     * return quickly to avoid blocking the background thread.
     */
    BACKGROUND,

    /**
     * Event handler methods are called in a separate thread. This is always independent from the posting thread and the
     * main thread. Posting events never wait for event handler methods using this mode. Event handler methods should
     * use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number
     * of long running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus
     * uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications.
     */
    ASYNC
}

哦,是个枚举类型。
POSTING:意思大概是,为了避免线程切换,在什么线程发的你接受默认就是什么线程

MAIN:主线程,也就是ui线程,不要做耗时操作哟

BACKGROUND:顾名思义,就是子线程啦。

ASYNC:异步,我感觉EventBus很贴心,异步都提供了。

5、EventBus还有一种使用,那就是EventBus的粘性事件(这里仅仅简单举个例子,我目前并没有在实际场景中用到)
依旧是这两个Activity

public class MainActivity extends AppCompatActivity {
    private Button button;
    private MyStudent myStudent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);//注册eventbus
        button = findViewById(R.id.main_btn);

        button .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, Main2Activity.class));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(MainActivity.this);
    }
//接收事件,EventBus3.0之后采用注解的方式
    @Subscribe(threadMode = ThreadMode.MAIN , sticky = true)//sticky是为了声明是粘性事件
    public void Event(MyStudent myStudent) {
        Log.e("MainActivity", myStudent.toString());
    }
}

看看Main2

public class Main2Activity extends AppCompatActivity {
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        button = findViewById(R.id.main2_btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyStudent myStudent = new MyStudent();
                myStudent.setName("eventbus");
                myStudent.setOld(2);
                myStudent.setSex(2);
                EventBus.getDefault().postSticky(myStudent);
               finish();
            }
        });
    }

为什么叫粘性事件呢?
先举个小例子,比如说:你定报纸,本来按理说你必须提前订阅了,在发报纸的时候才能收到。 而粘性事件是: 你别管他什么时候发的,就算他先发了报纸,那么你订阅的时候你也能收到这个报纸。(我觉得这个例子已经很形象了)
那么EventBus的粘性事件也是这样,如果他先发消息,发的时候你还没注册,不要紧,你什么时候注册什么时候接收,处理下面的事情。

学习的同学可以多打印log看看。多看多试。
这节课就到这里,下节课再见。

相关文章
|
22天前
|
监控 网络协议 Java
Tomcat源码解析】整体架构组成及核心组件
Tomcat,原名Catalina,是一款优雅轻盈的Web服务器,自4.x版本起扩展了JSP、EL等功能,超越了单纯的Servlet容器范畴。Servlet是Sun公司为Java编程Web应用制定的规范,Tomcat作为Servlet容器,负责构建Request与Response对象,并执行业务逻辑。
Tomcat源码解析】整体架构组成及核心组件
|
6天前
|
存储 缓存 Java
什么是线程池?从底层源码入手,深度解析线程池的工作原理
本文从底层源码入手,深度解析ThreadPoolExecutor底层源码,包括其核心字段、内部类和重要方法,另外对Executors工具类下的四种自带线程池源码进行解释。 阅读本文后,可以对线程池的工作原理、七大参数、生命周期、拒绝策略等内容拥有更深入的认识。
什么是线程池?从底层源码入手,深度解析线程池的工作原理
|
10天前
|
开发工具
Flutter-AnimatedWidget组件源码解析
Flutter-AnimatedWidget组件源码解析
|
6天前
|
设计模式 Java 关系型数据库
【Java笔记+踩坑汇总】Java基础+JavaWeb+SSM+SpringBoot+SpringCloud+瑞吉外卖/谷粒商城/学成在线+设计模式+面试题汇总+性能调优/架构设计+源码解析
本文是“Java学习路线”专栏的导航文章,目标是为Java初学者和初中高级工程师提供一套完整的Java学习路线。
|
7天前
|
监控 算法 数据可视化
深入解析Android应用开发中的高效内存管理策略在移动应用开发领域,Android平台因其开放性和灵活性备受开发者青睐。然而,随之而来的是内存管理的复杂性,这对开发者提出了更高的要求。高效的内存管理不仅能够提升应用的性能,还能有效避免因内存泄漏导致的应用崩溃。本文将探讨Android应用开发中的内存管理问题,并提供一系列实用的优化策略,帮助开发者打造更稳定、更高效的应用。
在Android开发中,内存管理是一个绕不开的话题。良好的内存管理机制不仅可以提高应用的运行效率,还能有效预防内存泄漏和过度消耗,从而延长电池寿命并提升用户体验。本文从Android内存管理的基本原理出发,详细讨论了几种常见的内存管理技巧,包括内存泄漏的检测与修复、内存分配与回收的优化方法,以及如何通过合理的编程习惯减少内存开销。通过对这些内容的阐述,旨在为Android开发者提供一套系统化的内存优化指南,助力开发出更加流畅稳定的应用。
19 0
|
20天前
|
图形学 iOS开发 Android开发
从Unity开发到移动平台制胜攻略:全面解析iOS与Android应用发布流程,助你轻松掌握跨平台发布技巧,打造爆款手游不是梦——性能优化、广告集成与内购设置全包含
【8月更文挑战第31天】本书详细介绍了如何在Unity中设置项目以适应移动设备,涵盖性能优化、集成广告及内购功能等关键步骤。通过具体示例和代码片段,指导读者完成iOS和Android应用的打包与发布,确保应用顺利上线并获得成功。无论是性能调整还是平台特定的操作,本书均提供了全面的解决方案。
80 0
|
20天前
|
开发者 算法 虚拟化
惊爆!Uno Platform 调试与性能分析终极攻略,从工具运用到代码优化,带你攻克开发难题成就完美应用
【8月更文挑战第31天】在 Uno Platform 中,调试可通过 Visual Studio 设置断点和逐步执行代码实现,同时浏览器开发者工具有助于 Web 版本调试。性能分析则利用 Visual Studio 的性能分析器检查 CPU 和内存使用情况,还可通过记录时间戳进行简单分析。优化性能涉及代码逻辑优化、资源管理和用户界面简化,综合利用平台提供的工具和技术,确保应用高效稳定运行。
31 0
|
20天前
|
机器学习/深度学习 TensorFlow 算法框架/工具
全面解析TensorFlow Lite:从模型转换到Android应用集成,教你如何在移动设备上轻松部署轻量级机器学习模型,实现高效本地推理
【8月更文挑战第31天】本文通过技术综述介绍了如何使用TensorFlow Lite将机器学习模型部署至移动设备。从创建、训练模型开始,详细演示了模型向TensorFlow Lite格式的转换过程,并指导如何在Android应用中集成该模型以实现预测功能,突显了TensorFlow Lite在资源受限环境中的优势及灵活性。
49 0
|
Android开发
android EventBus详解(一)
EventBus 是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent, Handler, BroadCast 在 Fragment,Activity,Service,线程之间传递消息.优点是开销小,使用方便,可以很大程度上降低它们之间的耦合,使得我们的代码更加简洁,耦合性更低,提升我们的代码质量。 类似的库还有 Otto ,今天就带大家一起研读 EventB
1161 0
|
Java Android开发 编译器
android EventBus详解(二)
上一节讲了EventBus的使用方法和实现的原理,下面说一下EventBus的Poster只对粘滞事件和invokeSubscriber()方法是怎么发送的。 Subscribe流程 我们继续来看EventBus类,分析完了包含的属性,接下来我们看入口方法register() 通过查看源码我们发现,所有的register()方法,最后都会直接或者间接的调用regi
909 0

推荐镜像

更多