Android项目实战(十三):浅谈EventBus
概述:
EventBus是一款针对Android优化的发布/订阅事件总线。
主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service。
线程之间传递消息.优点是开销小,代码更优雅,以及将发送者和接收者解耦。
---------------------------------------------------------------------------------------
下载:
类库源码:https://github.com/greenrobot/EventBus
jar包:http://download.csdn.net/detail/yy1300326388/8727699
---------------------------------------------------------------------------------------
使用:
build.gradle ,如果这种方式 不需要下载类库或者jar包 一句话即可导入
compile 'de.greenrobot:eventbus:2.4.0'
一、EventBus的使用,简单的来说就是5步:创建一个类(具体使用下面介绍),注册,发送消息,接收消息,解除注册
看一个Demo:
实现功能:有两个Activity,第一个Activity 跳转第二个Activity,第二个Activity 点击按钮发送消息,第一个Activity中的TextView显示接收到的这个消息信息

1、写下两个Activity的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity"> <TextView
android:layout_gravity="center"
android:id="@+id/show_msg"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> <Button
android:id="@+id/to_second_activity"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跳转第二个Activity"/> </LinearLayout>
activity_main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送一个消息"
android:id="@+id/send_msg" /> <Button
android:id="@+id/btn_finish"
android:text="销毁这个Activity,返回第一个Activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
activity_second
2、创建一个类,构造方法参数不固定,随便写,空类也可以,用于传递消息,看具体需求
package com.xqx.com.eventbusdemo;
public class MyMessage {
    private String string;
    public MyMessage(String string) {
        this.string = string;
    }
    public String getString() {
        return string;
    }
}
3、在你接收消息的页面(第一个Activity)注册和解除注册EventBus,并且获取和处理消息
在onCreate()方法中注册
EventBus.getDefault().register(this);
在onDestroy()方法中取消注册
EventBus.getDefault().unregister(this);
实现获取处理消息的方法,这里先使用onEventMainThread()方法,意思为接收到消息并在UI线程操作
public void onEventMainThread(MyMessage event) {
        String msg = "onEventMainThread收到了消息:" + event.getString();
        show_msg.setText(msg);
    }
完整代码:
package com.xqx.com.eventbusdemo; import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; import de.greenrobot.event.EventBus; public class MainActivity extends Activity { //按钮,开启第二个Activity
private Button to_second_activity;
//文本,显示接收到的消息
private TextView show_msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); to_second_activity = (Button) findViewById(R.id.to_second_activity);
show_msg = (TextView) findViewById(R.id.show_msg); //注册
EventBus.getDefault().register(this); //点击按钮进入到第二个Activity
to_second_activity.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,SecondActivity.class));
}
}); } //接收消息并处理
public void onEventMainThread(MyMessage event) {
String msg = "onEventMainThread收到了消息:" + event.getString();
show_msg.setText(msg);
} @Override
protected void onDestroy() {
super.onDestroy();
// 解除注册
EventBus.getDefault().unregister(this);
}
}
MainActivity.class
4、在要发送消息的页面发送消息
发送消息很简单,参数是你自己写的那个类
EventBus.getDefault().post(new MyMessage("this is a message"));
完整代码:
package com.xqx.com.eventbusdemo; import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button; import de.greenrobot.event.EventBus; public class SecondActivity extends Activity{ private Button send_msg;
private Button btn_finish;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second); send_msg = (Button) findViewById(R.id.send_msg);
btn_finish = (Button) findViewById(R.id.btn_finish); send_msg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(new MyMessage("this is a message"));
}
}); btn_finish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
}); }
}
SecondActivity.class
---------------------------------------------------------------------------------------
EventBus其他知识说明:
1、EventBus有四个不同的消息接收处理方法:
onEvent:
使用onEvent,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread:
使用onEventMainThread,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
onEventBackgroundThread:
使用onEventBackgrondThread,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync:
使用onEventAsync,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.
2、如果有多个地方发送消息,并且有多个消息处理函数,怎么确定哪个消息处理方法处理哪些消息呢?
这就看四个消息处理方法的参数。发送消息的参数是某一个类,接收的也必须是这个类,否则接收不到。如有有多个OnEvent()方法参数相同,那么这些方法都可以接收到消息。
---------------------------------------------------------------------------------------
总结:
register(注册)会把当前类中匹配的方法(onEvent开头的),存入一个map,而post会根据实参去map查找进行反射调用
Android项目实战(十三):浅谈EventBus的更多相关文章
- Android项目实战(二十九):酒店预定日期选择
		先看需求效果图: 几个需求点: 1.显示当月以及下个月的日历 (可自行拓展更多月份) 2.首次点击选择"开始日期",再次点击选择"结束日期" (1).如果&qu ... 
- (转载)Android项目实战(二十八):Zxing二维码实现及优化
		Android项目实战(二十八):Zxing二维码实现及优化 前言: 多年之前接触过zxing实现二维码,没想到今日项目中再此使用竟然使用的还是zxing,百度之,竟是如此牛的玩意. 当然,项目中 ... 
- Android安全开发之浅谈密钥硬编码
		Android安全开发之浅谈密钥硬编码 作者:伊樵.呆狐@阿里聚安全 1 简介 在阿里聚安全的漏洞扫描器中和人工APP安全审计中,经常发现有开发者将密钥硬编码在Java代码.文件中,这样做会引起很大风 ... 
- Android项目实战--手机卫士开发系列教程
		<ignore_js_op> banner131010.jpg (71.4 KB, 下载次数: 0) 下载附件 保存到相册 2 分钟前 上传 Android项目实战--手机卫士01- ... 
- Android项目实战(四十九):Andoird 7.0+相机适配
		解决方案类似: Android项目实战(四十):Andoird 7.0+ 安装APK适配 解决方法: 一.在AndroidManifest.xml 文件中添加 四大组件之一的 <provider ... 
- Android项目实战(三十二):圆角对话框Dialog
		前言: 项目中多处用到对话框,用系统对话框太难看,就自己写一个自定义对话框. 对话框包括:1.圆角 2.app图标 , 提示文本,关闭对话框的"确定"按钮 难点:1.对话框边框圆角 ... 
- (转载)Android项目实战(三十二):圆角对话框Dialog
		Android项目实战(三十二):圆角对话框Dialog 前言: 项目中多处用到对话框,用系统对话框太难看,就自己写一个自定义对话框. 对话框包括:1.圆角 2.app图标 , 提示文本,关闭对话 ... 
- (转载)Android项目实战(二十七):数据交互(信息编辑)填写总结
		Android项目实战(二十七):数据交互(信息编辑)填写总结 前言: 项目中必定用到的数据填写需求.比如修改用户名的文字编辑对话框,修改生日的日期选择对话框等等.现总结一下,方便以后使用. 注: ... 
- (转载)Android项目实战(十七):QQ空间实现(二)—— 分享功能 / 弹出PopupWindow
		Android项目实战(十七):QQ空间实现(二)—— 分享功能 / 弹出PopupWindow 这是一张QQ空间说说详情的截图. 分析: 1.点击右上角三个点的图标,在界面底部弹出一个区域,这个 ... 
- (转载)Android项目实战(二十八):使用Zxing实现二维码及优化实例
		Android项目实战(二十八):使用Zxing实现二维码及优化实例 作者:听着music睡 字体:[增加 减小] 类型:转载 时间:2016-11-21我要评论 这篇文章主要介绍了Android项目 ... 
随机推荐
- 深入学习jQuery自定义动画
			× 目录 [1]属性对象 [2]可选参数 [3]选项参数 前面的话 很多情况下,前面介绍的jQuery动画的简单效果无法满足用户的各种需求,那么就需要对动画有更多的限制,需要采取一些高级的自定义动画来 ... 
- PopupWindow底部弹出
			说明:从屏幕底部弹出PopupWindow,有弹出隐藏动画效果.背景设置透明度. 效果图如下: 1.MainActivity.java 显示popwindow,宽高跟屏幕大小一样,设置一个透明度背 ... 
- 通过配置http拦截器,来进行ajax请求验证用户登录的页面跳转
			在.NET中验证用户是否登录或者是否过期,若需要登录时则将请求转向至登录页面. 这个流程在进行页面请求时是没问题的,能正确进行页面跳转. 然而在使用xmlhttprequest时,或者jq的getJs ... 
- git与svn, tfs等源代码管理器的协同
			简单地说,这三个都是业界知名的源代码管理器.他们是有区别的,根本的区别在于git是分布式源代码管理器(每个本地都有完整的代码,及历史),而svn和tfs是集中式源代码管理器(只有服务器才有完整的历史, ... 
- linux管理进程的链表
			linux2.6.11的内核中,为了方便管理linux的进程,主要建了5种linux链表.每个链表节点之间的互联有两种方式,一种是hash节点之间的互联,通过hlist_node的数据结构来实现:另一 ... 
- SPRING多个占位符配置文件解析源码研究--转
			原文地址:http://www.cnphp6.com/archives/85639 Spring配置文件: <context:property-placeholder location=&quo ... 
- 2015-10-22 前思后想,决定重构表结构,免得这个APP死在数据表设计上
			新的设计稿出来了,如下,原来旧的是第二张 ------- 原来的评论级数只有2级,现在是不限,2级的意思是,用户评论该帖是一级,用户的评论能被人评论,这是第2级,评论评论的评论不能够再被 ... 
- JavaScript(Node.js)+ Selenium自动化测试
			Selenium is a browser automation library. Most often used for testing web-applications, Selenium may ... 
- 记一次由于Java泛型类型擦除而导致的问题,及解决办法
			中所周知,Java中的泛型并不像C++.C#一样是真正的泛型,其泛型是通过类型擦除来实现的.具体什么是类型擦除,可以参看这篇博文:http://icyfenix.iteye.com/blog/1021 ... 
- C#缓存操作
			1.缓存辅助方法类的接口代码: public interface IThrottleStore { /// <summary> /// 试图获取值 /// </summary> ... 
