作为一枚Android开发者,关于EventBus相信应该都听说过。要是用过就请忽略本文,本文讲得比较基础。
要是没用过,建议你花两分钟看看。

目前EventBus最新版本是3.0,本demo基于3.0编写的。

GitHub : https://github.com/greenrobot/EventBus
官方文档:http://greenrobot.org/eventbus/documentation

一、EventBus概述

EventBus是一个Android端优化的publish/subscribe消息总线,简化了应用程序内各组件间、组件与后台线程间的通信。

作为一个消息总线主要有三个组成部分:

  • 事件(Event)
  • 事件订阅者(Subscriber)
  • 事件发布者(Publisher)

    官方提供的关系图

二、EventBus用法

1、把EventBus依赖到项目

build.gradle添加引用

compile 'org.greenrobot:eventbus:3.0.0'

Maven

<dependency>
<groupId>org.greenrobot</groupId>
<artifactId>eventbus</artifactId>
<version>3.0.0</version>
</dependency>

或者直接下载EventBus 架包jar 放到项目中

2、构造发送消息类,也就是发送的对象
public class MainMessage{

    private String message;

    public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
}
}
3、注册/解除注册

EventBus.getDefault().register(this);//注册 EventBus.getDefault().unregister(this);//解除注册
4 、发送消息
EventBus.getDefault().post(new MainMessage("你好,爱开发");

ThreadMode总共四个:

  • MAIN UI主线程

  • POSTING 默认调用方式,在调用post方法的线程执行,避免了线程切换,性能开销最少

  • BACKGROUND 如果调用post方法的线程不是主线程,则直接在该线程执行。
    如果是主线程,则切换到后台单例线程,多个方法公用同个后台线程,按顺序执行,避免耗时操作

  • ASYNC 开辟新独立线程,用来执行耗时操作,例如网络访问。

来看一下源码,ThreadMode也就一个枚举,英文自己对照理解吧,不是很复杂

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
}
5 、事件处理
//ui主线程中执行
@Subscribe(threadMode = ThreadMode.Main) public void onMainEventBus(MainMessage msg) {
}
6、priority事件优先级

//priority越大,级别越高
@Subscribe(threadMode = ThreadMode.MAIN,priority = 100)
public void onEvent(MainMessage event) {
}
7、终止事件传递
// 注意中止事件传递,后续事件不在调用

@Subscribe
public void onEvent(MessageEvent event){
EventBus.getDefault().cancelEventDelivery(event) ;
}

下面我们来看一个完整的demo
先看一下效果图:

3.gif

新建两个activity,分别为MainActivity和 SecondActivity

其中MainActivity来放了五个按钮和一个文本框
SecondActivity只有一个按钮,点击按钮通知MainActivity页面更新。

看一下MainActivity主要代码:

     /**
* 主线程中执行
*
* @param msg
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMainEventBus(MainMessage msg) {
Log.e(TAG, msg.getMessage());
tv_desc.setText(msg.getMessage());
} /**
* 后台线程
*
* @param msg
*/
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onBackgroundEventBus(BackgroundMessage msg) {
Log.e(TAG, msg.getMessage());
} /**
* 异步线程
*
* @param msg
*/
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onAsyncEventBus(AsyncMessage msg) {
Log.e(TAG, msg.getMessage()); } /**
* 默认情况,和发送事件在同一个线程
*
* @param msg
*/
@Subscribe(threadMode = ThreadMode.POSTING)
public void onPostEventBus(PostingMessage msg) { Log.e(TAG, msg.getMessage());
}

按钮点击事件

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnMain:
EventBus.getDefault().post(new MainMessage("MainMessage"));
break;
case R.id.btnBackground:
EventBus.getDefault().post(new BackgroundMessage("BackgroundMessage"));
break;
case R.id.btnAsync:
EventBus.getDefault().post(new AsyncMessage("AsyncMessage"));
break;
case R.id.btnPosting:
EventBus.getDefault().post(new PostingMessage("PostingMessage"));
break;
case R.id.btn1:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
break; }
}

分别点击前面四个按钮时控制台按顺序输出:

点击前面四个按钮时控制台输出

SecondActivity页面点击发送消息的事件

EventBus.getDefault().post(new MainMessage("传递信息:aikaifa"));

在MianActivity页面我们就能接受到SecondActivity传递过来的信息了。
如果感兴趣想跑一下项目,源码请戳这里

作者:洪生鹏
链接:https://www.jianshu.com/p/f9aabe9d4eca
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

关于EventBus3.0使用,你看这篇就够了的更多相关文章

  1. 【HTTP】402- 深入理解http2.0协议,看这篇就够了!

    本文字数:3825字 预计阅读时间:20分钟 导读 http2.0是一种安全高效的下一代http传输协议.安全是因为http2.0建立在https协议的基础上,高效是因为它是通过二进制分帧来进行数据传 ...

  2. net core体系-web应用程序-4asp.net core2.0 项目实战(CMS)-第二章 入门篇-快速入门ASP.NET Core看这篇就够了

    .NET Core实战项目之CMS 第二章 入门篇-快速入门ASP.NET Core看这篇就够了   原文链接:https://www.cnblogs.com/yilezhu/p/9985451.ht ...

  3. .NET Core实战项目之CMS 第二章 入门篇-快速入门ASP.NET Core看这篇就够了

    作者:依乐祝 原文链接:https://www.cnblogs.com/yilezhu/p/9985451.html 本来这篇只是想简单介绍下ASP.NET Core MVC项目的(毕竟要照顾到很多新 ...

  4. [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了

    [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 本文首发自:博客园 文章地址: https://www.cnblogs.com/yilezhu/p/ ...

  5. ExpandoObject与DynamicObject的使用 RabbitMQ与.net core(一)安装 RabbitMQ与.net core(二)Producer与Exchange ASP.NET Core 2.1 : 十五.图解路由(2.1 or earler) .NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了

    ExpandoObject与DynamicObject的使用   using ImpromptuInterface; using System; using System.Dynamic; names ...

  6. Vue学习看这篇就够

    Vue -渐进式JavaScript框架 介绍 vue 中文网 vue github Vue.js 是一套构建用户界面(UI)的渐进式JavaScript框架 库和框架的区别 我们所说的前端框架与库的 ...

  7. Python GUI之tkinter窗口视窗教程大集合(看这篇就够了) JAVA日志的前世今生 .NET MVC采用SignalR更新在线用户数 C#多线程编程系列(五)- 使用任务并行库 C#多线程编程系列(三)- 线程同步 C#多线程编程系列(二)- 线程基础 C#多线程编程系列(一)- 简介

    Python GUI之tkinter窗口视窗教程大集合(看这篇就够了) 一.前言 由于本篇文章较长,所以下面给出内容目录方便跳转阅读,当然也可以用博客页面最右侧的文章目录导航栏进行跳转查阅. 一.前言 ...

  8. C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志

    C#实现多级子目录Zip压缩解压实例 参考 https://blog.csdn.net/lki_suidongdong/article/details/20942977 重点: 实现多级子目录的压缩, ...

  9. React入门看这篇就够了

    摘要: 很多值得了解的细节. 原文:React入门看这篇就够了 作者:Random Fundebug经授权转载,版权归原作者所有. React 背景介绍 React 入门实例教程 React 起源于 ...

  10. [转帖]Zookeeper入门看这篇就够了

    Zookeeper入门看这篇就够了 https://my.oschina.net/u/3796575/blog/1845035 Zookeeper是什么 官方文档上这么解释zookeeper,它是一个 ...

随机推荐

  1. C# WinForm 只运行一次的MDI子窗体

    public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void ToolColle ...

  2. 【转】清空mysql一个库中的所有表的数据

    方法1:重建库和表 用mysqldump --no-data把建表SQL导出来,然后drop database再create database,执行一下导出的SQL文件: 方法2:生成清空所有表的SQ ...

  3. JPA 对象关系映射之关联关系映射策略

    关联关系映射 关联关系映射,是映射关系中比较复杂的一种映射关系,总的说来有一对一.一对多和多对多几种关系.细分起来他们又有单向和双向之分.下面我们逐一介绍一下. 回页首 单向 OneToOne 单向一 ...

  4. 信息安全意识教育日历——By 安全牛

    安全牛:企业即使投入再好的信息安全技术和产品,也难以解决内部威胁以及社会工程等攻击手段,无法做到全面有效地保护企业信息资产.而通过开展员工的信息安全意识培训教育工作,不仅能降低企业风险.满足合规要求, ...

  5. SVN入门-2分钟教你入门

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u010540106/article/details/37317201   学习SVN首先我们应该知道 ...

  6. Redis四(Set操作)

    1.Set操作 Set集合就是不允许重复的列表 集合操作(无序) sadd(name,values) 1 # name对应的集合中添加元素 scard(name) 1 获取name对应的集合中元素个数 ...

  7. 【算法题12 解码方法decode way】

    1.来源LeetCode91 一条包含字母 A-Z 的消息通过以下方式进行了编码: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 给定一个只包含数字的非空字符串,请 ...

  8. Hadoop的IO操作

    Hadoop的API官网:http://hadoop.apache.org/common/docs/current/api/index.html   相关的包 org.apache.hadoop.io ...

  9. python16_day15【Django入门】

    一.Django基本 1.什么是框架 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表 ...

  10. Django中间件(含Django运行周期流程图)

    Django中的中间件(含Django完整生命周期图) Django中间件简介 django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,djang ...