【Android】使用EventBus进行线程间通讯

EventBus

简介

EventBus:github

EventBus是Android和Java的发布/订阅事件总线。

  • 简化组件之间的通信
    • 解耦事件发送者和接收者

    • 在 Activities, Fragments, background threads中表现良好

    • 避免复杂且容易出错的依赖关系和生命周期问题

Publisher使用post发出一个Event事件,Subscriber在onEvent()函数中接收事件。
EventBus 是一款在 Android 开发中使用的发布/订阅事件总线框架,基于观察者模式,将事件的接收者和发送者分开,简化了组件之间的通信,使用简单、效率高、体积小!下边是官方的 EventBus 原理图:

导入

Android Projects:

implementation("org.greenrobot:eventbus:3.2.0")

Java Projects:

implementation("org.greenrobot:eventbus-java:3.2.0")
<dependency>
    <groupId>org.greenrobot</groupId>
    <artifactId>eventbus-java</artifactId>
    <version>3.2.0</version>
</dependency>

配置

配置混淆文件

-keepattributes *Annotation*
-keepclassmembers class * {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

# If using AsyncExecutord, keep required constructor of default event used.
# Adjust the class name if a custom failure event type is used.
-keepclassmembers class org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}

# Accessed via reflection, avoid renaming or removal
-keep class org.greenrobot.eventbus.android.AndroidComponentsImpl

使用

简单流程

  1. 创建事件类
public static class MessageEvent { /* Additional fields if needed */ }
  1. 在需要订阅事件的地方,声明订阅方法并注册EventBus。
@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {
    // Do something
}
public class EventBusActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        //注册EventBus
        EventBus.getDefault().register(this);
    }
 
    //接收事件
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true, priority = 1)
    public void onReceiveMsg(MessageEvent message){
        Log.e("EventBus_Subscriber", "onReceiveMsg_POSTING: " + message.toString());
    }
 
    //接收事件
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 1)
    public void onReceiveMsg1(MessageEvent message){
        Log.e("EventBus_Subscriber", "onReceiveMsg_MAIN: " + message.toString());
    }
 
    //接收事件
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED, sticky = true, priority = 1)
    public void onReceiveMsg2(MessageEvent message){
        Log.e("EventBus_Subscriber", "onReceiveMsg_MAIN_ORDERED: " + message.toString());
    }
 
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消事件
        EventBus.getDefault().unregister(this);
    }
}
  1. 提交订阅事件
@OnClick(R2.id.send_event_common)
public void clickCommon(){
    MessageEvent message = new MessageEvent(1, "这是一条普通事件");
    EventBus.getDefault().post(message);
}
 
@OnClick(R2.id.send_event_sticky)
public void clickSticky(){
    MessageEvent message = new MessageEvent(1, "这是一条黏性事件");
    EventBus.getDefault().postSticky(message);
}

Subcribe注解

Subscribe是EventBus自定义的注解,共有三个参数(可选):threadMode、boolean sticky、int priority。 完整的写法如下:

@Subscribe(threadMode = ThreadMode.MAIN,sticky = true,priority = 1)
public void onReceiveMsg(MessageEvent message) {
    Log.e(TAG, "onReceiveMsg: " + message.toString());
}

priority

priority是优先级,是一个int类型,默认值为0。值越大,优先级越高,越优先接收到事件。

值得注意的是,只有在post事件和事件接收处理,处于同一个线程环境的时候,才有意义。

sticky

sticky是一个boolean类型,默认值为false,默认不开启黏性sticky特性,那么什么是sticky特性呢?

上面的例子都是对订阅者 (接收事件) 先进行注册,然后在进行post事件。

那么sticky的作用就是:订阅者可以先不进行注册,如果post事件已经发出,再注册订阅者,同样可以接收到事件,并进行处理。

ThreadMode 模式

POSITING:订阅者将在发布事件的同一线程中被直接调用。这是默认值。事件交付意味着最少的开销,因为它完全避免了线程切换。因此,对于已知可以在很短时间内完成而不需要主线程的简单任务,推荐使用这种模式。使用此模式的事件处理程序必须快速返回,以避免阻塞发布线程(可能是主线程)。

MAIN:在Android上,订阅者将在Android的主线程(UI线程)中被调用。如果发布线程是主线程,将直接调用订阅者方法,阻塞发布线程。否则,事件将排队等待交付(非阻塞)。使用此模式的订阅者必须快速返回以避免阻塞主线程。如果不是在Android上,行为与POSITING相同。

MAIN_ORDERED:在Android上,订阅者将在Android的主线程(UI线程)中被调用。与MAIN不同的是,事件将始终排队等待交付。这确保了post调用是非阻塞的。

BACKGROUND:在Android上,订阅者将在后台线程中被调用。如果发布线程不是主线程,订阅者方法将在发布线程中直接调用。如果发布线程是主线程,EventBus使用一个后台线程,它将按顺序传递所有事件。使用此模式的订阅者应尽量快速返回,以避免阻塞后台线程。如果不是在Android上,总是使用一个后台线程。

ASYNC:订阅服务器将在单独的线程中调用。这始终独立于发布线程和主线程。使用此模式发布事件从不等待订阅者方法。如果订阅者方法的执行可能需要一些时间,例如网络访问,则应该使用此模式。避免同时触发大量长时间运行的异步订阅者方法,以限制并发线程的数量。EventBus使用线程池来有效地重用已完成的异步订阅者通知中的线程。

/**
 * Each subscriber method has a thread mode, which determines in which thread the method is to be called by EventBus.
 * EventBus takes care of threading independently from the posting thread.
 * 
 * @see EventBus#register(Object)
 * @author Markus
 */
public enum ThreadMode {
    /**
     * Subscriber will be called directly 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 in 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,

    /**
     * On Android, subscriber will be called in Android's main thread (UI thread). If the posting thread is
     * the main thread, subscriber methods will be called directly, blocking the posting thread. Otherwise the event
     * is queued for delivery (non-blocking). Subscribers using this mode must return quickly to avoid blocking the main thread.
     * If not on Android, behaves the same as {@link #POSTING}.
     */
    MAIN,

    /**
     * On Android, subscriber will be called in Android's main thread (UI thread). Different from {@link #MAIN},
     * the event will always be queued for delivery. This ensures that the post call is non-blocking.
     */
    MAIN_ORDERED,

    /**
     * On Android, subscriber will be called in a background thread. If posting thread is not the main thread, subscriber 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. Subscribers using this mode should try to
     * return quickly to avoid blocking the background thread. If not on Android, always uses a background thread.
     */
    BACKGROUND,

    /**
     * Subscriber will be called in a separate thread. This is always independent from the posting thread and the
     * main thread. Posting events never wait for subscriber methods using this mode. Subscriber 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 subscriber methods at the same time to limit the number of concurrent threads. EventBus
     * uses a thread pool to efficiently reuse threads from completed asynchronous subscriber notifications.
     */
    ASYNC
}

相关文档

  • EventBus详解 (详解 + 原理)
  • 三幅图弄懂EventBus核心原理

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/674500.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

什么是公有云?与私有云的区别

公有云是指第三方提供商通过公共Internet为用户提供的云服务&#xff0c;用户可以通过Internet访问云并享受各类服务&#xff0c;包括并不限于计算、存储、网络等。公有云服务的模式可以是免费或按量付费。 微 思 | 好 课 推 荐 &#xff08;全国直播&#xff09; 【公有云】华…

Nginx企业级负载均衡:技术详解系列(18)—— 作为上传服务器

你好&#xff0c;我是赵兴晨&#xff0c;97年文科程序员。 在上一期的技术分享中&#xff0c;我们探讨了如何高效搭建Nginx下载服务器&#xff0c;并讨论了长连接优化策略。那么今天&#xff0c;咱们进一步了解Nginx的另一面——作为上传服务器的配置技巧。 作为上传服务器&a…

Ollama 如何排除故障

Ollama 日志 Mac 有时&#xff0c;Ollama 可能无法如你所愿运行。解决问题的一个好方法是查看日志。在 Mac 上&#xff0c;你可以通过运行以下命令来查看日志&#xff1a; cat ~/.ollama/logs/server.logLinux 在使用 systemd 的 Linux 系统上&#xff0c;可以用这个命令查…

Elastic Security 在 AV-Comparatives 的恶意软件防护测试中表现出色

作者&#xff1a;Jamie Hynds, Tamarian Del Conte, Roxana Gheorghe 针对真实恶意软件提供 100% 防护&#xff0c;零误报 Elastic Security 在最近的 AV-Comparatives 恶意软件防护测试中取得了显著的成绩&#xff0c;防护率达到 100%&#xff0c;且对真实恶意软件样本无误报…

Proteus 安装报错There is a problem with this Windows lnstaller package

Proteus 安装常见问题 1.安装秘钥(许可证)的时候报错 报错信息如下所示&#xff1a; There is a problem with this Windows lnstaller package. A program required for this instalt to compiete coutd notbe run,contact your support personnet or packagevendor. 这个是…

通用代码生成器应用场景六,为完善的应用系统收集需求

通用代码生成器应用场景六&#xff0c;为完善的应用系统收集需求 使用急就章功能可以开发一个简单的应用先凑和着使用。此应用系统也可以成为完善的应用系统的原型和祖先。如果您新规划一个完善的应用系统&#xff0c;您可以先使用通用代码生成器生成一个临时使用的系统&#x…

【VAE-base】VAE最简单代码实现(纯全连接层实现变分自编码机)

VAE &#xff08;Variational Autoencoder&#xff09; 代码&#xff1a;https://github.com/AntixK/PyTorch-VAE/blob/master/models/vanilla_vae.py 论文&#xff1a;Auto-Encoding Variational Bayes 核心参考1 https://github.com/lyeoni/pytorch-mnist-VAE/blob/master/p…

IPD推行成功的核心要素(八)市场管理与产品规划保证做正确的事情

产品开发管理是“正确地执行项目”&#xff0c;而市场管理及产品规划关注“执行正确的项目”&#xff0c;可以说后者对产品的成功更为关键。要实现产品的持续成功&#xff0c;还得从源头的市场管理抓起。成功的产品开发&#xff0c;必须面向市场需求&#xff0c;由需求牵引创新…

FlyMcu串口下载STLINK Utility

FlyMcu是串口下载 STLINK Utility是STLINK下载 生成hex文件 打开hex文件&#xff0c;点击开始编程 在编程之前&#xff0c;需要配置BOOT引脚&#xff0c;让STM32执行BootLoader&#xff0c;否则点击开始编程&#xff0c;程序会一直卡住。第一步STM32板上有跳线帽&#xf…

SuperSocket 服务器与客户端双向通讯

1、使用AppSession 的Send方法就可以向连接到的客户端发送数据。服务器端代码如下。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;//引入命名空间 using SuperSocket.Common; using SuperSocket.So…

【机器学习】逻辑回归:原理、应用与实践

&#x1f308;个人主页: 鑫宝Code &#x1f525;热门专栏: 闲话杂谈&#xff5c; 炫酷HTML | JavaScript基础 ​&#x1f4ab;个人格言: "如无必要&#xff0c;勿增实体" 文章目录 逻辑回归&#xff1a;原理、应用与实践引言1. 逻辑回归基础1.1 基本概念1.2 Sig…

leetCode-hot100-二分查找专题

二分查找 简介原理分析易错点分析例题33.搜索旋转排序数组34.在排序数组中查找元素的第一个和最后一个位置35.搜索插入位置240.搜索二维矩阵 Ⅱ 简介 二分查找&#xff0c;是指在有序&#xff08;升序/降序&#xff09;数组查找符合条件的元素&#xff0c;或者确定某个区间左右…

HTML静态网页成品作业(HTML+CSS)—— 香奈儿香水介绍网页(1个页面)

&#x1f389;不定期分享源码&#xff0c;关注不丢失哦 文章目录 一、作品介绍二、作品演示三、代码目录四、网站代码HTML部分代码 五、源码获取 一、作品介绍 &#x1f3f7;️本套采用HTMLCSS&#xff0c;未使用Javacsript代码&#xff0c;共有1个页面。 二、作品演示 三、代…

关于Acrel-2000E配电室综合监控系统的实际应用分析-安科瑞 蒋静

摘要:“三大工程”指的是保障性住房建设、“平急两用”公共基础设施建设、城中村改造&#xff0c;是我国在建设领域作出的重大决策部署&#xff0c;是根据房地产市场新形势推出的重要举措。其中城中村改造是解决群众急难愁盼问题的重大民生工程&#xff0c;该工程中配电房的建设…

新闻发稿:8个新闻媒体推广中最常见的错误-华媒舍

在数字时代&#xff0c;新闻媒体的推广手段已经越来越多样化。许多媒体在推广过程中常常会犯下一些常见错误。本文将会介绍八个新闻媒体在推广中最常见的错误&#xff0c;并希望能够帮助各位更好地规避这些问题。 1. 缺乏明确的目标受众 在进行推广前&#xff0c;新闻媒体需要…

华为OD机试 - 最大坐标值(Java 2024 D卷 100分)

华为OD机试 2024C卷题库疯狂收录中&#xff0c;刷题点这里 专栏导读 本专栏收录于《华为OD机试&#xff08;JAVA&#xff09;真题&#xff08;A卷B卷C卷&#xff09;》。 刷的越多&#xff0c;抽中的概率越大&#xff0c;每一题都有详细的答题思路、详细的代码注释、样例测试…

将HTML页面中的table表格元素转换为矩形,计算出每个单元格的宽高以及左上角坐标点,输出为json数据

export function huoQuTableElement() {const tableData []; // 存储表格数据的数组let res [];// 获取到包含表格的foreignObject元素const foreignObject document.getElementById(mydctable);if (!foreignObject){return ;}// 获取到表格元素let oldTable foreignObject…

Orange AIpro开箱上手

0.介绍 首先感谢官方给到机会&#xff0c;有幸参加这次活动。 OrangePi AIpro(8T)采用昇腾AI技术路线&#xff0c;具体为4核64位处理器AI处理器&#xff0c;集成图形处理器&#xff0c;支持8TOPS AI算力&#xff0c;拥有8GB/16GB LPDDR4X&#xff0c;可以外接32GB/64GB/128GB/2…

从小众到主流:KOC如何凭借微影响力塑造品牌传播新格局

随着数字化的飞速发展&#xff0c;KOC作为社交媒体上的一股新兴力量&#xff0c;正以其微小的粉丝基数和高度互动性&#xff0c;引发一场微影响力革命。与传统的KOL不同&#xff0c;KOC通常拥有较小的粉丝基数&#xff0c;但却能够凭借高度互动性和真实的消费者体验&#xff0c…

编写一个问卷界面 并用JavaScript来验证表单内容

倘若文章和代码中有任何错误或疑惑&#xff0c;欢迎提出交流哦~ 简单的html和css初始化 今天使用JavaScript来实现对表单输入的验证&#xff0c; 首先写出html代码如下&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset&qu…